How do I insert variable values into HTML tags in ERB templates?
29,787
Solution 1
<% office.map do |o| %>
<input id='city' name='company[company_office][0][city]' value='<%= o.office %>' type='text' />
<% end %>
or you could use the form helpers for that
Solution 2
Use embedded ruby(erb) tags,
<%= o.office %>
The only time you'd use #{o.office}
is when you're not using erb. In a helper method for example and you want to use your ruby in a string. But when you're in an html.erb
file, you have to use the erb tags.
Author by
maxfry
Updated on July 09, 2022Comments
-
maxfry almost 2 years
I have a partial like:
<% office.map do |o| %> <input id='city' name='company[company_office][0][city]' value=.... type='text' /> <% end %>
How can I insert a value like
o.office
into an attribute?value="#{o.office}"
does not work. -
maxfry almost 13 yearsno, form helpers i can't use, because i have specific name. Big thanks, i don't know, that i want to write quotes )
-
ardavis almost 13 years<%= content_tag :input, :id => "city", :name => "company[company_office][0][city]", :value => "#{o.office}", :type => "text" %> Could do it that way I suppose.
-
corroded almost 13 yearswhat do you mean specific name? also, traversing to a loop and creating inputs with the same id is not recommended. you should make your id and name dynamic.
-
lavapj about 11 yearsAgree with top voted answers.
<%= o.office %>
Just wanted to add that it's important for beginners to recognize distinction btwn erb tags with and without equals sign.<%= ... %>
versus<% ... %>
Tag with an equals sign indicates that enclosed code is an expression and renders code as a string. Used to embed line of code into template of to display contents of a variable. Tags without the equals sign commonly used for including loops / conditional logic in Ruby.