A small Clojure wrapper around jsoup, so you can parse HTML, escape text and sanitise untrusted markup from Clojure without writing Java interop yourself.
(require '[io.github.papachan.montalivet :as m])
(-> (m/parse "<p>1 < 2</p>" {:pretty-print false :escape-mode :extended})
m/body-html)
;; => "<p>1 < 2</p>"
(m/escape-html "<b>a & b</b>")
;; => "<b>a & b</b>"
(m/clean "<p onclick=\"x()\">Hi <script>alert(1)</script></p>")
;; => "<p>Hi </p>"
Add it to your deps.edn:
io.github.papachan/montalivet {:mvn/version "0.1.5"}
Install it locally from a clone:
clojure -T:build install
Montalivet runs on the JVM only. It is a wrapper around the Java library
jsoup, and it is published as .clj files, so it cannot be used from
ClojureScript.
parse(m/parse input)
(m/parse input opts)
Parses a full HTML document and returns a jsoup Document. input can be:
String of HTML,java.io.File,java.nio.file.Path,java.io.InputStream (read to its end, but not closed).(m/parse "<p>hi</p>")
(m/parse (java.io.File. "page.html"))
(m/parse (java.nio.file.Path/of "page.html" (make-array String 0)) {:charset "ISO-8859-1"})
parse accepts input-streams:
(with-open [in (clojure.java.io/input-stream "links.html")]
(mapv m/text (m/select (m/parse in) "a")))
;; => ["jsoup" "Clojure" "About & contact"]
You can select the correct charset with parse method:
(def latin1-file
(doto (java.io.File/createTempFile "montalivet" ".html")
(.deleteOnExit)
(spit "<p>caf�</p>" :encoding "ISO-8859-1")))
(m/select-one (m/parse latin1-file {:charset "ISO-8859-1"}) "p")
If charset is incorrect you can catch an Exception.
(try
(m/parse latin1-file {:charset :latin1})
(catch clojure.lang.ExceptionInfo e
[(ex-message e) (ex-data e)]))
| Option | Default | Description |
|---|---|---|
:pretty-print | true | Reformat the output when the document is rendered. |
:escape-mode | jsoup's default | :base, :xhtml or :extended. |
:base-uri | "", or the file's location for a File or Path | Base used to resolve relative links. |
:charset | detected | Charset of a File, Path or InputStream: a string such as "ISO-8859-1", or a java.nio.charset.Charset. When absent, jsoup reads it from a byte-order mark or a <meta> tag, and falls back to UTF-8. Ignored for a String. |
An unknown :escape-mode, an invalid :charset or any other type of input
throws an ex-info.
parse-fragment(m/parse-fragment html)
(m/parse-fragment html opts)
Parses an HTML string as a fragment of a document body. Returns a jsoup
Document whose body holds the fragment, so body-html and select work on
it. Takes the :pretty-print, :escape-mode and :base-uri options of
parse.
Unlike parse, every element stays in the body:
(def html "<title>t</title><p>x</p>")
(m/body-html (m/parse-fragment html {:pretty-print false}))
;; => "<title>t</title><p>x</p>"
(m/body-html (m/parse html {:pretty-print false}))
;; => "<p>x</p>" ; the title went to the head
(-> (m/parse-fragment "<a href=\"/a\">l</a>" {:base-uri "https://example.com/"})
(m/select-one "a")
(.absUrl "href"))
;; => "https://example.com/a"
Use it as an hickory-format data structure.
(require '[hickory.core :as h])
(h/as-hickory (.body (m/parse-fragment "<a href=\"foo\">foo</a>")))
body-html(m/body-html doc)
Returns the inner HTML of the document's <body> as a string. Fragments
without a <body> are wrapped in one by jsoup, so this works on partial
markup too:
(-> (m/parse "<b>a</b><i>b</i>" {:pretty-print false})
m/body-html)
;; => "<b>a</b><i>b</i>"
escape-html(m/escape-html s)
(m/escape-html s opts)
Escapes a string so it can be embedded as HTML text. It takes the same
:escape-mode option as parse (default :base).
(m/escape-html "a b" {:escape-mode :extended})
;; => "a b"
(m/escape-html "a b" {:escape-mode :xhtml})
;; => "a b" ; XHTML has no
Jsoup only escapes characters the output charset cannot represent. With the
default UTF-8, text such as café is returned unchanged, so this is not
identical to Apache Commons Text's escapeHtml4.
unescape-html(m/unescape-html s)
(m/unescape-html s opts)
Decodes HTML entities: named (&), decimal (B) and hexadecimal
(A). Unknown entities are left as they are. It reverses escape-html.
(m/unescape-html "a < b & c A")
;; => "a < b & c A"
(m/unescape-html (m/escape-html "<b>a & b</b>"))
;; => "<b>a & b</b>"
| Option | Default | Description |
|---|---|---|
:in-attribute | false | Decode as an attribute value: a named entity without its ; is kept when it is followed by = or a letter or digit, so "a=1©=2" stays as it is. |
clean(m/clean html)
(m/clean html opts)
Removes everything that is not allowed by a safelist, so untrusted markup can be embedded safely. Returns a string.
(m/clean "<p onclick=\"x()\">Hi <script>alert(1)</script><b>there</b></p>")
;; => "<p>Hi <b>there</b></p>"
;; keep only the text
(m/clean "<p>Hi <b>there</b></p>" {:safelist :none})
;; => "Hi there"
;; allow extra tags and attributes
(m/clean "<section class=\"c\"><b>x</b></section>"
{:add-tags [:section] :add-attributes {:section [:class]}})
;; => "<section class=\"c\"><b>x</b></section>"
;; relative links need a base URI, and unsafe ones lose their href
(m/clean "<a href=\"/a\">l</a>" {:base-uri "https://example.com/"})
;; => "<a href=\"https://example.com/a\">l</a>"
(m/clean "<a href=\"javascript:alert(1)\">l</a>" {:base-uri "https://example.com/"})
;; => "<a rel=\"nofollow\">l</a>"
;; HTML exported from Word: drop the <span> wrappers and the empty paragraphs
(m/clean (str "<p class=\"MsoNormal\"><span lang=\"ES\">Hola <i>mundo</i></span><o:p></o:p></p>"
"<p class=\"MsoNormal\"><span><o:p> </o:p></span></p>")
{:preset :word})
;; => "<p>Hola <i>mundo</i></p>"
| Option | Default | Description |
|---|---|---|
:safelist | :basic | :none, :simple-text, :basic, :basic-with-images or :relaxed. |
:add-tags, :remove-tags | Tags to allow or disallow, such as [:section]. | |
:add-attributes, :remove-attributes | Map of tag to attributes, such as {:a [:target] :all [:class]}. :all applies to every tag. | |
:base-uri | "" | Base used to resolve relative links. Without it they are removed. |
:preserve-relative-links | false | Keep relative URLs as they are. Still requires :base-uri. |
:pretty-print | false | Reformat the output. |
:escape-mode | :base, :xhtml or :extended. | |
:remove-empty | false | Remove the elements left with no content: no text other than whitespace or , and no void element such as <img> or <br>. An inline element holding only whitespace is unwrapped, so the space stays. A <br> at the end of a block with other content is removed; <p><br></p> is kept. Table cells are kept. |
:collapse-whitespace | false | Collapse whitespace the way a browser renders it: one space for each run, no space after another, none at the edges of blocks or between them. and <pre> are kept. |
:preset | Options for a common source of HTML. :word (Microsoft Word export) is {:remove-tags [:span] :remove-empty true :collapse-whitespace true}. Tags and attributes you pass are added to the preset's, other options replace its values. |
An unknown :safelist, :escape-mode or :preset throws an ex-info listing the
valid values. The exact output can differ between jsoup versions, so check
it against the version you use.
valid?(m/valid? html)
(m/valid? html opts)
Returns true when clean would remove nothing from html with the same
safelist. Use it to reject untrusted markup instead of cleaning it.
(m/valid? "<p>Hi <b>there</b></p>") ;; => true
(m/valid? "<p onclick=\"steal()\">Hi</p>") ;; => false
(m/valid? "<section>x</section>" {:add-tags [:section]}) ;; => true
It takes the :safelist, :add-tags, :remove-tags, :add-attributes,
:remove-attributes and :preserve-relative-links options of clean. Like
clean, it checks a fragment of a body, so a full document with <html> or
<head> is never valid. There is no base URI, so a relative link such as
/a is only valid with :preserve-relative-links true.
select and select-one(m/select doc css-query)
(m/select-one doc css-query)
Find elements of a parsed document with a
CSS selector.
select returns a vector of matching elements in document order (empty when
nothing matches), and select-one returns the first match or nil. Both work
on a document or on any element, in which case only its descendants are
searched. An empty or invalid selector throws an exception.
(def doc (m/parse "<div id=\"a\" class=\"x y\">
<a href=\"/1\" title=\"one\">One</a>
<a href=\"/2\">Two</a>
</div>"))
(map m/text (m/select doc "a"))
;; => ("One" "Two")
(map #(m/attr % :href) (m/select doc "a[href]"))
;; => ("/1" "/2")
| Function | Returns |
|---|---|
(m/text el) | The element's text, with entities decoded. |
(m/attr el k) | The value of attribute k (string or keyword), or nil. |
(m/abs-url el k) | Attribute k as an absolute URL, resolved against the document's :base-uri, or nil. |
(m/base-uri el) | The base URI used by abs-url, or nil. |
(m/attrs el) | All attributes as a map of keyword to string. |
(m/outer-html el) | The element's own markup, including its tag. |
(m/attrs (m/select-one doc "div"))
;; => {:id "a", :class "x y"}
(m/outer-html (m/select-one doc "a"))
;; => "<a href=\"/1\" title=\"one\">One</a>"
(-> (m/parse "<a href=\"/about\">About</a>" {:base-uri "https://example.com/"})
(m/select-one "a")
(m/abs-url :href))
;; => "https://example.com/about"
abs-url returns nil when the attribute is absent, or when it is relative
and the document has no base URI, like attr. jsoup returns "" in both
cases, but "" is truthy in Clojure, so nil works with if-let, some->,
or and keep:
(keep #(m/abs-url % :href) (m/select doc "a")) ; only the resolvable links
(or (m/abs-url img :src) "/default.png") ; a fallback
It does not check the URL: a javascript: link is returned as it is.
base-uri returns the :base-uri given to parse or parse-fragment, and
nil when there is none. A <base href> tag in the document replaces it.
For a File or a Path parsed without :base-uri, it is the absolute path
of the file, which is not a URL, so abs-url cannot resolve a link such as
/about against it. Pass :base-uri when you need absolute links.
(m/base-uri (m/parse "<p>x</p>" {:base-uri "https://example.com/"}))
;; => "https://example.com/"
(m/base-uri (m/parse "<p>x</p>"))
;; => nil
You can find the documentation here: API.
Run the tests with Kaocha:
clojure -M:dev:test:runner
Other tasks:
clojure -T:build jar # build target/montalivet-<version>.jar and pom.xml
clojure -T:build uberjar # standalone jar with all dependencies
clojure -T:build install # install into ~/.m2
clojure -M:clj-kondo --lint src test build.clj
clojure -M:format-check
See CONTRIBUTING.md and the CHANGELOG.
Copyright © 2026 papachan.
Licensed under the Apache License, Version 2.0. See LICENSE.
Can you improve this documentation? These fine people already did:
Dan Loaiza & DanEdit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |