How do I display html within html?

我的未来我决定 提交于 2019-12-11 02:55:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/14233777/how-do-i-display-html-within-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!