Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 如何在enlive中使用片段?_Clojure_Templating_Compojure_Enlive - Fatal编程技术网

Clojure 如何在enlive中使用片段?

Clojure 如何在enlive中使用片段?,clojure,templating,compojure,enlive,Clojure,Templating,Compojure,Enlive,我是一个在Clojure里把脚弄湿的Rails dev。我正试图用ERB做一些非常简单的事情,但我一辈子都无法用enlive解决 假设我在layout.html中有一个网站的简单布局文件: <!DOCTYPE html> <html> <head> </head> <body> </body> </html> 当请求转到“/”时,如何使其转换布局并将页眉和页脚片段插入其中?中的示例给出了很好的答案 警告。所有源

我是一个在Clojure里把脚弄湿的Rails dev。我正试图用ERB做一些非常简单的事情,但我一辈子都无法用enlive解决

假设我在layout.html中有一个网站的简单布局文件:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>

当请求转到“/”时,如何使其转换布局并将页眉和页脚片段插入其中?

中的示例给出了很好的答案


警告。所有源文件链接似乎都已断开。您需要在
https://github.com/swannodette/
在所有链接中,或者直接从教程项目中打开它们。

defsnippet只匹配html的特定部分(这就是它将选择器作为参数的原因),并对其进行转换。deftemplate获取整个html,并对其进行转换。此外,defsnippet返回Clojure数据结构,而deftemplates返回字符串向量,因此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")})})
代码段中使用的identity函数返回其参数,在本例中,该参数是由:#我的头根选择器选择的数据结构(我们不进行任何转换)。如果您想在head.html中包含所有内容,可以使用enlive附带的根选择器步骤

您可以使用以下内容查看从defsnippet生成的html:

(print (apply str (enlive/emit* (my-snippet))))
我还推荐教程: 还有Brian Marick的一篇文章,详细介绍了defsnippet和deftemplate宏的工作原理

最后一个提示,您可以使用enlive附带的sniptest宏来尝试选择器和转换:

(enlive/sniptest "<p>Replace me</p>"
[:p] (enlive/content "Hello world!"))
;= "<p>Hello world!</p>"
(enlive/sniptest“替换我”
[:p](enlive/content“Hello world!”)
;= “你好,世界!


谢谢!对未来读者的更正。行(enlive/defsippet header“path/to/header.html”[:#我的头根]标识)应该在选择器后面有一个向量。所以应该是:(enlive/defsnippet header“path/to/header.html”[:#我的头根][]标识)。页脚的代码片段也一样。啊,错过了那个。我已相应地更新了示例。
(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))
(print (apply str (enlive/emit* (my-snippet))))
(enlive/sniptest "<p>Replace me</p>"
[:p] (enlive/content "Hello world!"))
;= "<p>Hello world!</p>"