Question

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.

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top