Enlive - 从文件中包装HTML标签

时间:2014-01-27 23:48:23

标签: clojure enlive

所以我在logout.html中有以下HTML:

<form id="log_out" name="log_out" action="/log_out" method="post">
  <input type="submit"
         value="Log Out!">
  </input>
</form>

看起来我需要一些函数来读取logout.html作为活动节点(至少我认为wrap需要节点;我实际上并不确定。)

(html/defsnippet nav "templates/nav.html" [:ul]
      []
      [:ul] (html/append
                  (html/wrap :li (html/SOME-FUNCTION-IDK "templates/logout.html"))))

2 个答案:

答案 0 :(得分:2)

不确定这是否是最佳方式,但您可以将logout.html的内容定义为一个活跃的代码段。片段类似于模板,但返回节点,并且还可以选择性地抓取文件的一部分(在下面的示例中,选择器是:#log_out,表示具有id =“log_out”的表单元素)。

(html/defsnippet logout-form "templates/logout.html" [:#log_out] 
  [])

然后像:

(html/defsnippet nav "templates/nav.html" [:ul]
  []
  [:ul] (html/append
          ((html/wrap :li) (logout-form))))) ;; untested! ymmv

答案 1 :(得分:1)

我最终不得不修改过度思考的答案才能让它发挥作用。

(defn extract-body
  "Enlive uses TagSoup to parse HTML. Because it assumes that it's dealing with
   something potentially toxic, and tries to detoxify it, it adds <head> and
   <body> tags around any HTML you give it. So the DOM returned by html-resource
   has these extra tags which end up wrapping the content in the middle of our
   webpage. We need to strip these extra tags out."
  [html]
  (html/at html [#{:html :body}] html/unwrap))

(html/defsnippet logout "templates/logout.html" [html/root] [])

wrap的工作原理是它包含给定标记中的选定元素。因此,在这种情况下,会选择#log_out并使用li标记进行包装。

(html/defsnippet nav "templates/nav.html" [html/root]
      []
      [:ul] (html/append (extract-body (logout)))
      [:#log_out] (html/wrap :li))

它绝对不像我想的那么干净,但它确实有用。