Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 586
haXs Avatar asked Dec 17 '25 15:12

haXs


1 Answers

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>
like image 88
Jacob Brown Avatar answered Dec 19 '25 05:12

Jacob Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!