2012-06-11 38 views
2

我是Ruby/HAML的新手,並試圖簡化我的簡單需求的部分語法。例如,我想創建一個部分,將通過變量輸出以下HTML:儘可能簡單的部分語法通過haml的本地人

<figure class="foo"> 
    <img src="path/to/img.png" /> 
    <figcaption>caption text here</figcaption> 
</figure> 

我希望創建一個幫助,以獲得部分語法的東西近似:

@(figure).foo { 
    img: "path/to/img.png", 
    caption: "caption text here" 
} 

這個簡單的語法是可能的嗎?有更好的方法嗎?

回答

1

肯定的:

figure_helper(:foo, 'path/to/img.png', 'caption text here') 

然後在您的幫助文件:

def figure_helper(cls='default_cls', img='rails.png', caption='uh oh! forgot caption!') 
<<STMT 
    <figure class="#{cls}"> 
    <img src="#{img}" /> 
    <figcaption>#{caption}</figcaption> 
    </figure> 
STMT 
end 

注意:如果你不熟悉定義字符串這裏語句的語法,確保關閉<<STMT開始在第一列。

在IRB:

1.9.2p0 :016 > def figure_helper(cls='default_cls', img='rails.png', caption='uh oh! forgot caption!') 
1.9.2p0 :017?> <<STMT 
1.9.2p0 :018"> <figure class="#{cls}"> 
1.9.2p0 :019">  <img src="#{img}" /> 
1.9.2p0 :020">  <figcaption>#{caption}</figcaption> 
1.9.2p0 :021"> </figure> 
1.9.2p0 :022"> STMT 
1.9.2p0 :023?> end 
=> nil 
1.9.2p0 :025 > puts figure_helper(:foo, 'path/to/img.png', 'caption text here') 
    <figure class="foo"> 
    <img src="path/to/img.png" /> 
    <figcaption>caption text here</figcaption> 
    </figure> 
=> nil 
+0

謝謝,這是很有幫助的。你介意給我看幫手代碼的樣子嗎?如果某些變量是可選的,助手會如何處理? –

+0

發表了一個工作解決方案。 – Anil

相關問題