Reputation: 141
I've seen a few similar questions but none that appear generalisable to my situation.
I have to use HTML mixed with Ruby for some tags. There are two methods I have found.
Method A
<input id="<%= id %>" />
This works fine for the most part, however, if the id is an empty string or nil, then it will still return HTML like so:
<input id />
Problem: I'd prefer to exclude the 'id' tag completely if the variable is an empty string or nil.
Method B
<input <%= "id=#{id}" unless id.blank? %> />
If the id is an empty string it will return the desired result
<input />
Problem: If the id has multiple spaces, however, it causes issue (this is more relevant for tags like 'value'). For example if 'id' is "lorem ispum dolor sit amet" it would output:
<input id="lorem" ipsum dolor sit amet />
Does anyone have a better way of conditionally including HTML attributes? Note, I know I can use Rails HTML helpers like text_field_tag, but I'd like to find a solution without using those.
EDIT: I plan to do this with multiple HTML attributes (e.g. <input id="<%= id %>" value="<%= value %>" name="<%= name %>" ... />
Upvotes: 3
Views: 3009
Reputation: 14352
Use the tag helper:
<%= tag.input id: id %>
If the id
is blank it will output:
<input>
Upvotes: 1
Reputation: 2663
There are two main problems
When id equals lorem" ipsum dolor sit amet
, this ERB snippet
<input <%= "id=#{id}" unless id.blank? %> />
generates this HTML.
<input id=lorem ipsum dolor sit amet />
In HTML5, quotes are optional unless the attribute value contains spaces, so only the first word is the id. We can resolve this issue by quoting the attribute. I'm using the string literal %()
syntax here so that we don't have to escape double quotes.
<input <%= %(id="#{id}") unless id.blank? %> />
This outputs the id that we want.
<input id="lorem ipsum dolor sit amet" />
id
attributes may not contain whitespace
id
's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID.
This is the sort of thing that generally works completely fine until an edge case shows up and it suddenly doesn't. The browser does a lot of work to make sure that invalid HTML still renders, but we can make things easier on ourselves in the long run by sticking to the spec. 😉
Upvotes: 1
Reputation: 441
You can use the full structure of the condition :
<% unless id.blank? %>
<input id="<%= id %>" />
<% else %>
<input />
<% end %>
Upvotes: 0