2012-12-25 29 views
2

我已经在我的表扩展html类的推荐模式是什么?

<% if user.company.nil? %> 
    <tr class="error"> 
<% else %> 
    <tr> 
<% end %> 
    <td><%= user.name %></td> 
</tr> 

以下<tr>标签我想补充另一个if语句

<% if user.disabled? %> 
    <tr class="disabled"> 
<% end %> 

所以当两个这样的语句是true我希望收到:

<tr class="error disabled"> 

我知道我应该将其移至助手,但如何编写扩展类的良好大小写声明取决于o这些陈述?

回答

0

你可以尝试一个辅助方法,像

def user_table_row(user) 
    css = "" 
    css = "#{css} error" if user.company.nil? 
    css = "#{css} disabled" if user.disabled? 

    content_tag :tr, class: css 
end 

不知道有多好,这将在表行的情况下工作,因为你将要嵌套TD它

UPDATE内:这里被更新版本屈服TD代码块

def user_table_row(user) 
    css = # derive css, using string or array join style 

    options = {} 
    options[:class] = css if css.length > 0 

    content_tag :tr, options do 
    yield 
    end 
end 

然后在视图

<%= user_table_row(user) do %> 
    <td><%= user.name %></td> 
<% end %> 
+0

“#{} CSS错误” ......您会收到类= “错误” –

2
def tr_classes(user) 
    classes = [] 
    classes << "error" if user.company.nil? 
    classes << "disabled" if user.disabled? 
    if classes.any? 
    " class=\"#{classes.join(" ")}\"" 
    end 
end 

<tr<%= tr_classes(user) %>> 
    <td><%= user.name %></td> 
</tr> 

但良好的作风是:

def tr_classes(user) 
    classes = [] 
    classes << "error" if user.company.nil? 
    classes << "disabled" if user.disabled? 
    if classes.any? # method return nil unless 
    classes.join(" ") 
    end 
end 

<%= content_tag :tr, :class => tr_classes(user) do -%> # if tr_classes.nil? blank <tr> 
    <td><%= user.name %></td> 
<% end -%> 
+0

'content_tag:TR' 给标签与收盘: –

+0

看起来很酷,但嗯,我不喜欢这个''[] .tap''语法:)但现在最好的选择,谢谢 – tomekfranek

+0

避免.tap如果你不喜欢它) –