[英]Parse object to attribute-value with hamlc
我正在使用CoffeeScript和HAML。 我有對象列表:
{
title: "Title"
url: "http://example.com"
image_url: "img.png"
attributes: {
target: '_blank'
}
}
{
// ...
}
我有一個模板:
- for item in @model.data
%a.menu-item{"href": item.url}
我可以以某種方式解析“屬性”(如果存在)並添加到%a.menu-item
元素以獲得<a href="[item.ur]" target="_blank">
如果要合並哈希中的所有屬性,這應該可以工作:
%a.menu-item{item['attributes'], "href" => item['url']}
要有條件地包含標簽元素,請使用define? 訣竅在於ternery-將屬性值設置為nil將其刪除。 ( https://gist.github.com/orioltf/3145400 )
作為示例(嘗試使用一些快速的ruby代碼來模擬您的情況)
- _h1 = {'title' => 'Title', 'url' => "http://example.com", 'image_url'=> "img.png", 'attributes'=> {'target'=> '_blank'}}
- _h2 = {'title' => 'Title2', 'url' => "http://example2.com", 'image_url'=> "img2.png"}
- $data_list = [_h1, _h2]
- class Model; def data() $data_list end end
- @model = Model.new
- for item in @model.data
%a.menu-item{:href => item['url'],
:target => (defined? item['attributes']['target']) ? item['attributes']['target'] : nil}
請注意,我在使用哈希訪問器。 根據您設置的對象,所使用的框架,可以使用我所做的,item.url,item.get('url')等。
您可以使用haml test.haml test.html進行測試,希望可以幫助您入門。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.