Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Top Level Tags HAML w/o using partials

What is an elegant way to conditionally add a higher level html element without repeating the inner contents? How can this be achieved without using partials (all content in one file)?

For example, say I have this content and I want to wrap all the content in a div based on some condition so the (img, 'some code' x 3) is not being repeated.

- unless p.product_url.nil?
  #myDiv
    %img{src: img_url}
    some code
    some code
    some code
- else
  %img{src: img_url}
  some code
  some code
  some code
like image 529
Bijan Avatar asked Dec 07 '25 09:12

Bijan


1 Answers

- content_for :inner_contents do
  %img{src: img_url}
  some code
  some code
  some code

- unless p.product_url.nil?
  #myDiv
    = yield :inner_contents
- else
  = yield :inner_contents

This is based off of https://stackoverflow.com/a/7240476/605707, as mentioned by Deefour.

like image 198
Nick McCurdy Avatar answered Dec 09 '25 23:12

Nick McCurdy