2011-05-04 38 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