【问题标题】:How do I display html within html?如何在 html 中显示 html?
【发布时间】:2013-01-09 11:00:58
【问题描述】:

假设我有一个 html 文档:

<html>test<html>

我想在浏览器中显示该代码。然后我会创建类似的东西:

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

为了制作中间的gubbins,我有一个功能:

(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 是否内置了这个?没找到。

【问题讨论】:

    标签: html clojure escaping


    【解决方案1】:

    有几个选项:

    1. 自己动手。
    2. 使用公共 StringEscapeUtils
    3. 如果您使用的是 Hiccup,它带有一个功能。

    对于#3,只需使用hiccup.core 中的h 函数即可。

    对于#2,将[org.apache.commons/commons-lang3 "3.1"] 添加到您的依赖项中,然后您可以使用编码

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

    对于 #1,您可以使用 hiccup 使用的函数。它很小:

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

    这些解决方案都可以。

    【讨论】:

      猜你喜欢
      • 2023-01-24
      • 2015-03-31
      • 2011-08-31
      • 2011-01-08
      • 2019-01-25
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多