在rails上使用ruby为haml创建一个帮助器或东西

时间:2010-03-26 13:46:18

标签: ruby-on-rails ruby haml

我正在使用haml和我的rails应用程序,我有一个问题如何将这个haml代码插入到html文件中的最简单方法:

<div clas="holder">
 <div class=top"></div>
  <div class="content">
   Content into the div goes here
  </div>
 <div class="bottom"></div>
</div>

我想在我的haml文档中使用它:

%html
 %head
 %body
  Maybee some content here.
  %content_box #I want to get the code i wrote inserted here
   Content that goes in the content_box like news or stuff
 %body

有更简单的方法吗?


我收到此错误:

**unexpected $end, expecting kEND**

使用此代码:

# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
 def content_box(&block)
  open :div, :class => "holder" do # haml helper
   open :div, :class => "top"
    open :div, :class => "content" do
      block.call
    open :div, :class => "bottom"
  end
 end
end

2 个答案:

答案 0 :(得分:37)

您也可以使用haml_tag

def content_box
  haml_tag :div, :class => "holder" do
    haml_tag :div, :class => "top"
    haml_tag :div, :class => "content" do
      yield
    haml_tag :div, :class => "bottom"
  end
end

和haml

%html
  %head
  %body
    Maybee some content here.
    = content_box do
      Content that goes in the content_box like news or stuff

答案 1 :(得分:3)

典型的解决方案是使用部分。

或_helper.rb文件中的辅助方法:

def content_box(&block)
  open :div, :class => "holder" do # haml helper
    open :div, :class => "top"
    open :div, :class => "content" do
      block.call
    end
    open :div, :class => "bottom"
  end
end

以haml:

%html
  %head
  %body
    Maybee some content here.
    = content_box do
      Content that goes in the content_box like news or stuff