【问题标题】:Mixing Ruby and HAML混合 Ruby 和 HAML
【发布时间】:2012-01-16 05:35:54
【问题描述】:

我想使用 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,但也许我错过了一些东西。无论如何,我愿意接受建议。

【问题讨论】:

  • 不推荐的解决方案。改用助手。对于标签,使用content_tag(:tag, "content") 方法

标签: ruby ruby-on-rails-3 haml


【解决方案1】:

您永远不需要在 Rails 的视图文件中定义方法。无论语言是 ERb、Haml 还是其他任何语言,都是如此。相反,将方法放在帮助文件中,然后在您的视图中调用它:

app/helpers/some_helper.rb

module SomeHelper
  def button(text)
    content_tag :div, text, :class => :button
  end
end

app/views/whatever/view.html.haml

= button 'My First Button'
= button 'My Second Button'

如果您最终需要大量复杂的帮助程序,请改用 partials,和/或研究 Cells gem。

【讨论】:

    【解决方案2】:

    你想做的都是可能的。有一些documentation from the HAML page,这是我的猜测,你可以在你的情况下如何使用它:

    def my_thing
      haml_engine = Haml::Engine.new(".div_class
         this is my attempt at HAML")
      haml_engine.render
    end
    

    话虽如此,我建议你不要这样做,而是使用 Rails(内置)助手或 Presenter 模式(通过我自己的 delegate_presenterDraper 出现在 Rails 社区中创建复杂的 HTML 小部件/元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      相关资源
      最近更新 更多