2013-01-21 156 views
9

我是一名Rails開發者,我的腳在Clojure中受潮。我試圖做一些與再培訓局一樣非常簡單的事情,但我無法爲我的生活弄清楚它是否有用。如何在活動中使用片段?

說我有對的layout.html一個網站一個簡單的佈局文件:

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

而我的這些片段,例如,header.html中和footer.html這簡單的路線。

(deftemplate layout "layout.html" []) 

(defroutes home-routes 
    (GET "/" [] layout)) 

我怎樣才能使它所以每當一個請求轉到「/」它改變了佈局,並插入頁眉和頁腳片段成嗎?

回答

11

defsnippet只匹配你的html的一個特定部分(這就是爲什麼它需要一個選擇器作爲參數),並進行轉換。 deftemplate佔用整個html,並對其進行轉換。此外,defsnippet返回一個Clojure數據結構,而deftemplates返回一個字符串向量,所以defsnpet通常在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")})}) 

你的情況,你想要的東西,如:

了header.html:

<div id="my-header-root"> 
... 
</div> 

的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)) 

片段中使用的標識函數返回它的參數,在這種情況下,它是由:#my-header-root選擇器(我們不做任何轉換)選擇的數據結構。如果你想在head.html中包含所有的東西,你可以使用根選擇器的步驟,這是有活力的。

您可以查看使用這樣的事情從defsnippet生成的HTML:

(print (apply str (enlive/emit* (my-snippet)))) 

我還建議教程:https://github.com/swannodette/enlive-tutorial/ 以及如何defsnippet和自定義模板中宏的一些更詳細的一個由布賴恩·馬里克工作。

(enlive/sniptest "<p>Replace me</p>" 
[:p] (enlive/content "Hello world!")) 
;= "<p>Hello world!</p>" 
+1

感謝:

最新提示,你可以選擇和轉換使用隨enlive的sniptest宏實驗!對未來的讀者進行更正。該行((enlive/defsnippet header「path/to/header.html」[:#my-header-root] identity)在選擇器之後應該有一個向量。所以它應該是:(enlive/defsnippet header「path/to/header.html」[:#my-header-root] [] identity)。與頁腳的defsnpet相同。 –

+1

啊,錯過了那一個。我已經更新了相應的例子。 – ebaxt

0

enlive tutorial中有很好的例子。

警告。所有的源文件鏈接似乎都被打破您需要在https://github.com/swannodette/之後的所有鏈接中插入enlive-tutorial/blob/master/,或直接從教程項目打開它們。