Chr*_*Bui 9 clojure templating compojure enlive
我是一个Rails开发人员在Clojure中弄湿我的脚.我正在尝试用ERB做一些非常简单的事情,但我无法在生活中把它弄清楚.
假设我在layout.html中有一个简单的网站布局文件:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我有这些片段,例如header.html和footer.html以及这条简单的路线.
(deftemplate layout "layout.html" [])
(defroutes home-routes
(GET "/" [] layout))
Run Code Online (Sandbox Code Playgroud)
如果请求转到"/",我怎样才能改变布局并将页眉和页脚片段插入其中?
eba*_*axt 11
defsnippet只匹配你的html的特定部分(这就是为什么它将选择器作为参数),并转换它.deftemplate获取整个html,并对其进行转换.此外,defsnippet返回一个Clojure数据结构,而deftemplate返回一个字符串向量,因此defsnippet通常在deftemplate中使用.
为了让您了解代码段(或选择器)返回的数据如下所示:
(enlive/html-snippet "<div id='foo'><p>Hello there</p></div>")
;=({:tag :div, :attrs {:id "foo"}, :content ({:tag :p, :attrs nil, :content ("Hello there")})})
Run Code Online (Sandbox Code Playgroud)
在你的情况下你想要的东西:
header.html中:
<div id="my-header-root">
...
</div>
Run Code Online (Sandbox Code Playgroud)
Clojure代码:
(enlive/defsnippet header "path/to/header.html" [:#my-header-root] []
identity)
(enlive/defsnippet footer "path/to/footer.html" [enlive/root] []
identity)
(enlive/deftemplate layout "layout.html" [header footer]
[:head] (enlive/content header)
[:body] (enlive/append footer))
(defroutes home-routes
(GET "/" [] (layout (header) (footer))
Run Code Online (Sandbox Code Playgroud)
片段中使用的标识函数返回它的参数,在这种情况下,它是由:#my-header-root选择器选择的数据结构(我们不进行任何转换).如果你想在head.html中包含所有内容,你可以使用enlive附带的root选择器步骤.
您可以使用以下内容查看defsnippet生成的html:
(print (apply str (enlive/emit* (my-snippet))))
Run Code Online (Sandbox Code Playgroud)
我还推荐教程:https://github.com/swannodette/enlive-tutorial/ 和Brian Marick 的教程,了解defsnippet和deftemplate宏如何工作的更多细节.
最后一点提示,您可以使用enlive附带的sniptest宏来试验选择器和转换:
(enlive/sniptest "<p>Replace me</p>"
[:p] (enlive/content "Hello world!"))
;= "<p>Hello world!</p>"
Run Code Online (Sandbox Code Playgroud)