Spencer K.
Spencer K.

Reputation: 469

Add multiple conditional CSS classes in HTML with Rails string interpolation

I am using Rails and trying to conditionally add a div height based on a query string param. There are four possible values for the v query string param: 1, 2, 3, or 4. When v=3 or v=4, I want to display the heading-row-2 class. Otherwise, I want to display the heading-row class.

I'm looking for something along the lines of these two:

<%= content_tag :div, class: "row #{'heading-row-2' ? (params[:v] == 3 || 4) : 'heading-row'}"%>

<div class="row <%='heading-row-2' ? (params[:v] == 3 || 4) : 'heading-row'%> ">

Note that I also need:
- A 'row' tag.
- To add more html inside the div.

Upvotes: 1

Views: 685

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33470

You can add heading-row in any case. In case the parameter v is 3 or 4 you interpolate the value -2 to the class option:

<%= content_tag :div, class: "row heading-row#{'-2' if params[:v].in?(['3', '4'])}" %>

<div class="row heading-row<%= '-2' if params[:v].in?(['3', '4']) %>">

The second way seems easier to read.


Notice

params[:v] == 3 || 4

Might not be what you expect, as it means "if the value of params[:v] is equal to 3 then return true otherwise return 4".

Upvotes: 2

Related Questions