2
votes

I am new to Ruby/HAML and am attempting to simplify a partial syntax for my simple requirements. For example, I want to create a partial that will pass variables to output the following HTML:

<figure class="foo">
  <img src="path/to/img.png" />
  <figcaption>caption text here</figcaption>
</figure>

I'm looking to create a helper to get the partial syntax to something approximating:

@(figure).foo {
  img: "path/to/img.png",
  caption: "caption text here"
}

Is a syntax this simple possible? Is there a better approach?

1

1 Answers

1
votes

Sure:

figure_helper(:foo, 'path/to/img.png', 'caption text here')

Then in your helper file:

def figure_helper(cls='default_cls', img='rails.png', caption='uh oh! forgot caption!')
<<STMT
  <figure class="#{cls}">
    <img src="#{img}" />
    <figcaption>#{caption}</figcaption>
  </figure>
STMT
end

Note: In case you are not familiar with the here statement syntax of defining strings, make sure that the closing <<STMT starts in the 1st column.

In irb:

1.9.2p0 :016 > def figure_helper(cls='default_cls', img='rails.png', caption='uh oh! forgot caption!')
1.9.2p0 :017?>   <<STMT
1.9.2p0 :018">   <figure class="#{cls}">
1.9.2p0 :019">     <img src="#{img}" />
1.9.2p0 :020">     <figcaption>#{caption}</figcaption>
1.9.2p0 :021">   </figure>
1.9.2p0 :022"> STMT
1.9.2p0 :023?>   end
 => nil 
1.9.2p0 :025 > puts figure_helper(:foo, 'path/to/img.png', 'caption text here')
  <figure class="foo">
    <img src="path/to/img.png" />
    <figcaption>caption text here</figcaption>
  </figure>
 => nil