在任意地方活跃和标记

时间:2014-01-21 11:54:13

标签: clojure enlive

这是enlive 1.1.5的内容(为了清晰起见,添加了源格式/空格更改):

blogen.core> (html/sniptest "<html><head>
                                <title><span id=\"foo\"/></title>
                              </head></html>"
                            [:#foo] (html/substitute "f"))
"<html><head><title></title></head></html>f"

blogen.core> (html/sniptest "<html><head>
                                <title><span id=\"foo\"/></title>
                              </head></html>"
                            [:#foo] (constantly "f"))
"<html><head><title></title></head></html>f"

我想在HTML源代码中编写一个常量前缀,以便我的clojure代码不会从我的最终内容中饱和。但正如上面的剪辑所示,我span内的title标签不可用。使用核心函数constantly的第二个测试表明,任何更多自定义编写的转换都不可能更好地成功。

我不想使用${vars},因为它们在模板中看起来很愚蠢。我更喜欢在模板中写出体面的例子,然后enlive可以在没有损坏的情况下替换。

动机

我很乐意将模板编写为HTML,并使用span元素定义id作为变量占位符。但是enlive并没有根据需要解析span内的title个标签。保持较少的收集。例子:

<title><span id="article-name"/> - <span id="my-site" /></title>

<p>Welcome, <span id="visitor-ip" /></p>

1 个答案:

答案 0 :(得分:1)

根据HTML5 spec<title>标记的ContentModel是Text,这意味着其中不允许使用HTML元素。

解析HTML的Enlive部分可能只处理有效的HTML,因此它无法与<span>标记内的<title>标记很好地配合使用。

你有几个选择。

可以设置<title>标签的内容而不是完全替换它,如下所示:

(html/sniptest "<html><head><title>Placeholder</title></head></html>"
               [:title] (html/content "foo"))

;; => <title>foo</title>

或者,如果您想保持标题的一部分不变,可以使用appendprepend

(html/sniptest "<html><head><title>Some Title</title></head></html>"
                [:title] (html/append " - sub page"))

;; => <title>Some Title - sub page</title>

修改

我知道你说你想避免${vars},但在这种情况下,他们碰巧完全按照你的意愿行事......

(html/sniptest "<html><head><title>${my-site} - ${article-name}</title></head></html>"
               [:title] (html/transform-content
                          (html/replace-vars
                             {:article-name "Using Enlive for good and evil"
                              :my-site "Clojure Weekly"})))

;; =>  <title>Clojure Weekly - Using Enlive for good and evil</title>