How to dynamically style HTML elements in Rails based on an object’s property

I was helping someone with a project and they wanted to change the CSS class of an image based on a property of an object that it was attached to. The person was used to using AngularJS’s ng-class and wanted similar functionality.

For demonstration purposes let’s assume we have an ActiveRecord model named User that has a property named “awesome” which can be true or false. Let’s also assume we have an image named “doggie.jpg” in our app/assets/images folder.

The CSS file.

.awesome-true{
  border: 3px solid green;
}

.awesome-false{
  border: 3px solid red;
}

In the view (@user is a single instance of the User model)

<%= image_tag "doggie.jpg", :class => "awesome-#{@user.awesome}" %>

The result when true.

<img class="awesome-true" src="/assets/doggie-6708b9ff28cb5d2d941ed3b01dfe977c611a0ea07dc04249dbdce4514245c303.jpg" alt="Doggie 6708b9ff28cb5d2d941ed3b01dfe977c611a0ea07dc04249dbdce4514245c303">

The result when false.

<img class="awesome-false" src="/assets/doggie-6708b9ff28cb5d2d941ed3b01dfe977c611a0ea07dc04249dbdce4514245c303.jpg" alt="Doggie 6708b9ff28cb5d2d941ed3b01dfe977c611a0ea07dc04249dbdce4514245c303">

Leave a Reply