如何在html中显示html? [英] How do I display html within html?

查看:202
本文介绍了如何在html中显示html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个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>))


$ b b

为我执行上述转换:

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

我的问题是:是否够好,或者我会碰到html,转换中断?



第二个问题可能是:clojure有这个内置?我找不到。

解决方案

有几个选项:



  1. 使用commons StringEscapeUtils

  2. 如果您使用hiccup,函数。

对于#3,只需使用 h hiccup.core



对于#2,添加 [org.apache.commons / commons-lang33.1] 到您的依赖项,然后可以

 (org.apache.commons.lang3.StringEscapeUtils / escapeHtml4your string)

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

 (defn escape-html 
将特殊字符更改为HTML字符实体
[text]
(.. ^ String(as-str text)
(替换&& amp;)
(替换<& lt ;)
(替换>& gt;)
(替换\& quot;)))

这些解决方案都很好。


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.

解决方案

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.

这篇关于如何在html中显示html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆