2010-03-26 29 views
23

我使用HAML與我的Rails應用程序的紅寶石和我有一個問題是如何最簡單的方法插入此HAML代碼到一個HTML文件:創建HAML一個幫手或一些與在軌道上

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

我想在我這樣的哈姆文件中使用它:

%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 

回答

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 
+0

請閱讀我對其他答案的評論。在應用速度方面有效嗎? – Lisinge 2010-03-26 14:11:41

+0

速度的差距真的是零。輔助方法很好用。 – shingara 2010-03-26 14:44:50

3

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

或者在你的_helper.rb文件中的helper方法:

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 
+1

好的,謝謝。我在哪裏把_helper.rb,我如何加載它? 對不起,新的軌道。剛剛使用PHP – Lisinge 2010-03-26 14:08:51

+0

,我想發送一個參數給函數來改變盒子的顏色,它的工作方式就像改變div上的class class =「holder_ @ color_here」一樣,我該怎麼做? – Lisinge 2010-03-26 14:10:28

+4

幾種版本的'open'方法已被替換爲'haml_tag'。改爲使用'haml_tag'。 如果您希望幫助程序在應用程序中的任何位置都可用,請將其放入app/helpers/application.rb中。如果您只希望它可用於FoosController的視圖,請將它放在app/helpers/foos.rb中。 – 2010-03-26 22:31:18