2

我是 Ruby/HAML 的新手,我正在尝试为我的简单需求简化部分语法。例如,我想创建一个将传递变量以输出以下 HTML 的部分:

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

我正在寻找一个帮助器来使部分语法接近于:

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

这么简单的语法可能吗?有更好的方法吗?

4

1 回答 1

1

当然:

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

然后在您的帮助文件中:

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

注意:如果您不熟悉定义字符串的 here 语句语法,请确保结束<<STMT从第一列开始。

在 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 
于 2012-06-11T04:08:24.750 回答