Reputation: 17470
Suppose I've got an html document:
<html>test<html>
And I want to display that code in a browser. Then I'd create something like:
<html><body>
<pre><html>test<html></pre>
</body></html>
To make the gubbins in the middle I have a function:
(defn html-escape [string]
(str "<pre>" (clojure.string/escape string {\< "<", \> ">"}) "</pre>"))
which does the above transformation for me:
user> (html-escape "<html>test<html>")
"<pre><html>test<html></pre>"
My question is: is that good enough, or am I going to come across html that will make that transformation break?
And a secondary question might be: does clojure have this built in? I can't find it.
Upvotes: 2
Views: 1028
Reputation: 32625
There are a few options:
For #3, just use the h
function in hiccup.core.
For #2, add [org.apache.commons/commons-lang3 "3.1"]
to your dependencies, and then you can encode with
(org.apache.commons.lang3.StringEscapeUtils/escapeHtml4 "your string")
For #1, you can use the function hiccup uses. It's pretty small:
(defn escape-html
"Change special characters into HTML character entities."
[text]
(.. ^String (as-str text)
(replace "&" "&")
(replace "<" "<")
(replace ">" ">")
(replace "\"" """)))
Any of these solutions are fine.
Upvotes: 3