2013-01-09 95 views
2

假設我有一個html文件:如何在html中顯示html?

<html>test<html> 

我想顯示在瀏覽器的代碼。然後我想創建這樣的:

<html><body> 
<pre>&lt;html&gt;test&lt;html&gt;</pre> 
</body></html> 

爲了使格賓斯中間我有一個函數:

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

它可以完成上述轉變對我來說:

user> (html-escape "<html>test<html>") 
"<pre>&lt;html&gt;test&lt;html&gt;</pre>" 

我問題是:這足夠好了,還是我會遇到可以使轉換中斷的html?

而第二個問題可能是:clojure是否有內置的?我找不到它。

回答

3

有幾個選項:

  1. 滾你自己。
  2. 使用commons StringEscapeUtils
  3. 如果您使用打嗝,它帶有一個這樣的功能。

對於#3,只需使用h功能hiccup.core

#2,添加[org.apache.commons/commons-lang3 "3.1"]到你的依賴,然後你可以編碼與

(org.apache.commons.lang3.StringEscapeUtils/escapeHtml4 "your string") 

#1,你可以使用函數打嗝使用。這是相當小的:

(defn escape-html 
    "Change special characters into HTML character entities." 
    [text] 
    (.. ^String (as-str text) 
    (replace "&" "&amp;") 
    (replace "<" "&lt;") 
    (replace ">" "&gt;") 
    (replace "\"" "&quot;"))) 

任何這些解決方案都很好。