混合 Ruby 和 HAML
我想使用 Ruby 方法来生成经常出现在我的页面中的标记。本质上,我想做与此等效的操作(ERB 文件):
<% def create_button(text) %>
<div class="button"><%= text %></div>
<% end %>
...
<%
create_button("My First Button")
create_button("My Second Button")
# etc.
%>
显然,这个想法是,每当我需要按钮时,我都会使用 create_button
。
我想象的 Ruby/HAML 解决方案看起来像这样:
def create_button(text)
%div.button text
end
create_button("My First Button")
create_button("My Second Button")
其输出将与第一个块相同。
有办法做到这一点吗?如果没有,最终我会寻找一种优雅的方法来使用 Ruby 辅助方法生成标记。如果您对如何执行此操作有任何建议,我很想听听。我是 Rails 新手,不太喜欢 ERB,但也许我错过了一些东西。无论如何,我愿意接受建议。
I'd like to use Ruby methods to generate the markup that appears frequently in my pages. In essence, I want to do the equivalent of this (ERB file):
<% def create_button(text) %>
<div class="button"><%= text %></div>
<% end %>
...
<%
create_button("My First Button")
create_button("My Second Button")
# etc.
%>
Obviously the idea is that any time I need a button, I use create_button
.
The Ruby/HAML solution I'm imagining would look something like this:
def create_button(text)
%div.button text
end
create_button("My First Button")
create_button("My Second Button")
The output of this would be the same as the first block.
Is there a way to do this? If not, ultimately I'm looking for an elegant way to generate markup with Ruby helper methods. If you have any suggestions for how to do this, I'd like to hear it. I'm new to Rails and don't really like ERB, but maybe I'm missing something. Anyway, I'm open to suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您永远不需要在 Rails 的视图文件中定义方法。无论语言是 ERb、Haml 还是其他语言,都是如此。相反,将该方法放入帮助程序文件中,然后在视图中调用它:
app/helpers/some_helper.rb
app/views/whatever/view.html.haml
如果您最终需要很多复杂的帮助程序,请使用部分代替,和/或调查细胞宝石。
You should never need to define a method within a view file in Rails. That's true whether the language is ERb, Haml, or anything else. Instead, put the method in a helper file, then just call it in your view:
app/helpers/some_helper.rb
app/views/whatever/view.html.haml
If you wind up needing a lot of complex helpers, use partials instead, and/or investigate the Cells gem.
你想做的事情是可能的。有一些来自 HAML 页面的文档,这是我的猜测在你的情况下使用它:
话虽如此,我建议你不要做类似的事情,而是使用 Rails(内置)帮助程序或 Presenter 模式(通过我自己的 delegate_presenter 或 Draper 创建复杂的 HTML 小部件/元素
What you want to do is possible. There's some documentation from the HAML page, and here's my guess how you might use it in your situtation:
Having said that, I suggest you don't do something like that, and instead use Rails (built-in) helpers or the Presenter pattern (emerging in the Rails community via my own delegate_presenter or Draper to create complex HTML widgets/elements