andrewcockerham
andrewcockerham

Reputation: 2706

How can I add multiple classes to a Rails form input with erb?

So this is what I want to do:

<% for x in 6..10 %>
  <%= form_for(current_user.responses.new, html:{class: 'col-xs-2 col-md-1 col-lg-1 vcenter center'}) do |f, index| %>
    <%= f.text_field :response_value, label: false, :class => "my-width <%= x %>" %>
  <% end %>
<% end %>

But it doesn't work. I want to have two classes on the input field, one being a normal css class using html. The other using an erb variable, in this case 'x'.

I've tried

<%= f.text_field :response_value, label: false, :class => "my-width center vcenter", :class => x %>

Which only assigns the second :class, and overrides the first.

How can I assign both these classes ("my-width" and x) to the form input field?

Upvotes: 0

Views: 3226

Answers (3)

shashwat
shashwat

Reputation: 1002

Posting a new answer since Rails4 has a much better way of doing this:

<%= f.text_field :response_value, label: false, class: ["my-width", x] %>

Upvotes: 3

Ninigi
Ninigi

Reputation: 1311

<%= f.text_field :response_value, label: false, :class => "my-width <%= x %>" %>

This line doesnt really make any sense, since you are putting an erb tag to the string inside an erb tag... Try

<%= f.text_field :response_value, label: false, :class => "my-width #{x}" %>

Upvotes: 1

DickieBoy
DickieBoy

Reputation: 4956

<%= f.text_field :response_value, label: false, :class => "my-width <%= x %>"

Isnt valid ruby syntax. Im suprised your not getting an error.

Use string interpolation:

<%= f.text_field :response_value, label: false, :class => "my-width #{x}" %>

Also its worth noting you should use html classes that are solely a number.

Something like:

:class => "my-width-#{x}"

Is valid.

Upvotes: 1

Related Questions