Search code examples
rubyhamlmustache

If clause in haml using variable from mustache


Similar to this question, I want to use if clause in haml file, specifically only display the image when there is actually image url. The code is

%div{ :class => "attachment {{ attachment_type }}" }
  %a{ :href => "{{ attachment_url }}", :target=> "_blank"}
    %img.image{ :src => "{{ attachment_pic_url }

and I was trying something like:

:plain
<%if {{attachment_pic_url}}.present? %>
  <% { %>
    <img class="image" src="{{ attachment_pic_url}}"  %> %>"/>
  <% } %>

but it complains 'Unclosed tag'. Any idea of this issue? Or is there a better way to do this?


Solution

  • Mustache is logic-less as there are no if statements.

    We can use tags instead.

    In your case -

    {{#attachment_pic_url}}
    %a{ :href => "{{ attachment_url }}", :target=> "_blank"}
      %img.image{ :src => "{{ attachment_pic_url }}" }
    {{/attachment_pic_url}}
    

    If the attachment_key_url key does not exist, or exists and has a value of null, undefined, false, 0, or NaN, or is an empty string or an empty list, the block will not be rendered.

    Refer https://github.com/janl/mustache.js#false-values-or-empty-lists.