1

I saw a similar question, but I believe there are certain differences here, that is this code can't be fixed that way. Let's consider the following code:

- if image['href']
    %a{href: image['href']}
        <some markup>
- else
    <some markup>

Is there anything I can do to avoid duplication without moving code to the other file?

UPD It appears my question is a duplicate of this one.

Community
  • 1
  • 1
x-yuri
  • 16,722
  • 15
  • 114
  • 161

1 Answers1

2

Haml 4.1 (currently in beta – it might be version 5 when it’s released) contains a haml_tag_if method that will do what you want:

- haml_tag_if image['href'], :a, href: image['href'] do
  some markup

This will produce either:

<a href='foo'>
  some markup
</a>

or just

some markup

depending on whether image['href'] is truthy.

If you don’t want to upgrade yet, you can add the method yourself as a helper, see this answer to a similar question: https://stackoverflow.com/a/8595810/214790 (the code there is basically the same as the new code in Haml itself).

Community
  • 1
  • 1
matt
  • 78,533
  • 8
  • 163
  • 197
  • Could you elaborate on how to upgrade to haml 4.1 beta? – x-yuri Mar 20 '14 at 18:04
  • 1
    @x-yuri `gem install haml --pre` will install the gem. If you’re using Bundler add `gem 'haml', '4.1.0.beta.1'` to your `Gemfile`. – matt Mar 20 '14 at 18:09