How can I conditionally wrap some HAML content in a tag?

前端 未结 2 2053

How can I use a condition to decide whether to output a surrounding tag in HAML? I\'m trying to create the DRY version of the code below.

- if i_should_link          


        
2条回答
  •  醉梦人生
    2020-12-03 17:15

    I think odin's suggestion to use a partial is probably the best in most situations.

    However, as an alternate solution, I found a thread where Nathan Weizenbaum suggested defining this method:

    def haml_tag_if(condition, *args, &block)
      if condition
        haml_tag *args, &block
       else
         yield
       end
    end
    

    Whatever is in the block would always be rendered, but the wrapping tag would appear or not based on the condition.

    You would use it as follows:

    - haml_tag_if(planning_to_mail?, :div, :id => 'envelope') do
       %p I'm a letter
    

    If planning_to_mail? evaluates true, you'd get:

    I'm a letter

    If it evaluates false, you'd get:

    I'm a letter

    He floated the idea of adding this to Haml::Helpers, but that doesn't appear to have happened yet.

提交回复
热议问题