根据变量改变循环中div的类

时间:2013-08-13 13:14:29

标签: ruby-on-rails erb

我有这个循环:

<% @checks.each do |check| %>
  <tr>
    <td><%= check.name %></td>
    <td><%= check.type.name %></td>
    <td><%= check.department.name %></td>
    <td><%= check.due_by %></td>
    <td><span class="label label-success"><%= check.state.name %></span></td>


    <td><%= link_to 'Edit', edit_check_path(check) %></td>
    <td><%= link_to 'Delete', check, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>    

并且取决于check.sate.name等于什么,我需要它有一个不同的类, 例如,如果它等于complete,则它具有类"label label-success",如果它是incomplete,则它具有"label label-danger"等。

2 个答案:

答案 0 :(得分:1)

这是帮助方法的用途。变化

<td><span class="label label-success"><%= check.state.name %></span></td>

类似

<td><span class="label label-<%= state_label(check.state.name) %>"><%= check.state.name %></span></td>

然后在state_label

中定义app/helpers/check_helper.rb
def state_label(state)
  case state
    when "complete"
      "success"
    when "incomplete"
      "danger"
    else
      "some-default-state"
end

我更喜欢装饰器/演示器模式而不是像这样的助手的实现。一个很棒的宝石是https://github.com/drapergem/draper给定一些State,您可以向label_class添加StateDecorator方法,这样您就可以使用装饰Check来执行此类操作

<td><span class="label label-<%= check.state.label_class %>"><%= check.state.name %></span></td>

label_class可能看起来像这样

def label_class
  case model.state
    when "complete"
      "success"
    when "incomplete"
      "danger"
    else
      "some-default-state"
end

答案 1 :(得分:0)

你可以写一个小帮手,例如:

def check_state_label(state_name)
  label_class = case state_name
                when "complete"
                  "label label-success"
                when "incomplete"
                  "label label-danger"
                else
                  "label"
                end
  content_tag :span, state_name, class: label_class
end

并以这种方式称呼它:

<td><%= check_state_label(check.state.name) %></td>