John Lawrence Aspden
John Lawrence Aspden

Reputation: 17470

How do I display html within html?

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>&lt;html&gt;test&lt;html&gt;</pre>
</body></html>

To make the gubbins in the middle I have a function:

(defn html-escape [string] 
  (str "<pre>" (clojure.string/escape string {\< "&lt;", \> "&gt;"}) "</pre>"))

which does the above transformation for me:

user> (html-escape "<html>test<html>")
"<pre>&lt;html&gt;test&lt;html&gt;</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

Answers (1)

Rayne
Rayne

Reputation: 32625

There are a few options:

  1. Roll your own.
  2. Use commons StringEscapeUtils
  3. If you're using hiccup, it comes with a function for this.

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 "&"  "&amp;")
    (replace "<"  "&lt;")
    (replace ">"  "&gt;")
    (replace "\"" "&quot;")))

Any of these solutions are fine.

Upvotes: 3

Related Questions