1

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.

1
  • A better alternative to string interpolation in complex cases may be to create an array of classes and just join the array with spaces. Commented Oct 7, 2019 at 1:35

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. I like how concise it is. However, I'm getting the following error: no implicit conversion of Array into String. I'm using the second option you provided. Not sure if this matters, but this is what is in Parameters: {"v"=>"3"}.
Sorry, I mixed the order there. It should be params[:v].in?(['3', '4']), can you try again?
That did it. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.