0

I am using CoffeeScript and HAML. I have objects list:

{
  title: "Title"
  url: "http://example.com"
  image_url: "img.png"
  attributes: {
    target: '_blank'
  }
}
{
  // ...
}

And I have a template:

- for item in @model.data
  %a.menu-item{"href": item.url}

Can I somehow parse "attributes" if it is exists and add to %a.menu-item element to get <a href="[item.ur]" target="_blank">

acidernt
  • 2,173
  • 2
  • 19
  • 33

2 Answers2

0

If you want to merge all attributes from your hash, this should work:

%a.menu-item{item['attributes'], "href" => item['url']}
EugZol
  • 6,476
  • 22
  • 41
0

To conditionally include a tag element, use defined? The trick is in the ternery - setting the attribute value to nil will remove it. (https://gist.github.com/orioltf/3145400)

As an example (trying to mock up your situation with some quick ruby code)

- _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}

Note here that I am using hash accessors. Depending on your your objects are set up, what framework you are using, you may use what i did, item.url, item.get('url'), etc.

You can test it out with haml test.haml test.html Hope that gets you started.

Steve Tarver
  • 3,030
  • 2
  • 25
  • 33