haXs
haXs

Reputation: 89

How to set a css class based on content in rails

I am very new to Rails and web app development in general so appologies if this is something basic,

My issue is I am looking for a way in rails to set a CSS class based on the value of an object.

Using the bootstrap framework inside my rails application I have a table that shows a list of orders which each have a state, it can be in various states for example: "Created, In Progress , Exception"

Depending on what state that order is in I would like to use a CSS label such as <span class="label label-warning>" for exception state or <span class="label label-success"> for Created or In Progress.

I was thinking perhaps have a helper method somewhere and call that from the view to work it out? Not sure if I have missed something basic as I am sure this is something that comes up in every application?

orders\index.html.erb
<div>
<h1>Listing orders</h1>

<table>
  <thead>
    <tr>
      <th>Customer</th>
      <th>Order ID</th>
      <th>Order State</th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @orders.each do |order| %>
      <tr>
        <td><%= order.customer.name %></td>
        <td><%= order.id %></td>
        <td> <span class="label label-warning><%= order.state %></span></td>
        <td><%= link_to 'Show', order %></td>
        <td><%= link_to 'Edit', edit_order_path(order) %></td>
        <td><%= link_to 'Destroy', order, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <td><%= link_to 'Exception', exception_order_path(order), method: :post %>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

Upvotes: 3

Views: 2486

Answers (1)

Jacob Brown
Jacob Brown

Reputation: 7561

Not sure if this is what you are looking for, but you can do something like this:

content_tag(:td, '', :class => (@obj == 'x' ? 'something' : 'somethingElse'))

If your condition testing is complicated, yes, I would use a helper method. Then you could do something like:

content_tag(:td, '', :class => name_of_helper_method(@obj))

where the helper method returns a string for the class name you want to set.

Edit: this might be what you are looking for:

<td><span class="label <%= order.state == 'Created' ? 'label-success' : 'label-warning' %>"></span></td>

Upvotes: 6

Related Questions