2011-05-04 58 views
5

我喜歡使用Haml助手,但多年來事情發生了一些變化。舊的方法是簡單地連接到緩衝區。下面是我有:使用Haml助手返回字符串

def confirmation_table(field) 
    # Be certain that if the user is logged in, his/her email and name show 
    if field.respond_to? :user 
    haml_tag('tr') { 
     haml_tag('th', 'Email:') 
     haml_tag('td', field.user.email) 
    } 
    haml_tag('tr') {  
     haml_tag('th', 'Name:') 
     haml_tag('td', field.user.full_name) 
    } 
    else 
    haml_tag('tr') { 
     haml_tag('th', 'User Information:') 
     haml_tag('td', 'Not specified.') 
    } 
    end 

    field.class.columns.collect{|col| col.name}.reject{|col| 
    col =~ /_at$/ || 
    col =~ /_on$/ || 
    col =~ /_id$/ || 
    col == 'id'}.each do |col| 
    haml_tag('tr') { 
     haml_tag('th', ActiveSupport::Inflector::humanize(col)) 
     haml_tag('td', typeize(field, col)) 
    } 
    end 
end 

這當然可以,可在我看來訪問簡單,如:

- confirmation_table(@f) 

然而,它更有意義(我)這個返回一個字符串。我看不到haml_capture如何提供相同的結構化能力。任何提示?

回答

6

裹在capture_haml您的通話haml_tag

def confirmation_table(field) 
    capture_haml do 
    if field.respond_to? :user 
     haml_tag(:tr) do 
     haml_tag('th.email', 'Email:') 
     haml_tag('td.email', field.user.email) 
     end 
     # ... 
    end 
    end 
end 

他們會被捕獲並通過capture_haml返回。

+0

您是否願意完成您的示例,以便它是獨立的並且最小可行? – 2013-01-28 20:40:24

+0

你是什麼意思?添加一些'haml_tag'調用?或者在HAML視圖中使用此幫助程序的示例? – 2013-01-28 21:31:46

+0

是的,添加多個'haml_tag'調用。我知道這聽起來很愚蠢,但我試圖在沒有安裝RoR的情況下使用命令行中的'haml',並且我看到一些大多數人不會遇到的問題。因此,我想要一個完整的(但很小的)例子。 – 2013-01-28 21:45:50