0

我正在使用 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">

4

2 回答 2

0

要有条件地包含标签元素,请使用定义?诀窍在于三元组 - 将属性值设置为 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 对其进行测试,希望可以帮助您入门。

于 2015-08-27T21:09:17.377 回答
0

如果要合并哈希中的所有属性,这应该有效:

%a.menu-item{item['attributes'], "href" => item['url']}
于 2015-08-25T19:49:03.110 回答