[英]Conditional HTML Attribute using Rails ERB
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.对于某些标签,我必须将 HTML 与 Ruby 混合使用。 There are two methods I have found.我找到了两种方法。
Method A方法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:这在大多数情况下都可以正常工作,但是,如果 id 是空字符串或 nil,那么它仍然会返回 HTML,如下所示:
<input id />
Problem: I'd prefer to exclude the 'id' tag completely if the variable is an empty string or nil.问题:如果变量是空字符串或 nil,我宁愿完全排除“id”标签。
Method B方法B
<input <%= "id=#{id}" unless id.blank? %> />
If the id is an empty string it will return the desired result如果 id 是空字符串,它将返回所需的结果
<input />
Problem: If the id has multiple spaces, however, it causes issue (this is more relevant for tags like 'value').问题:但是,如果 id 有多个空格,则会导致问题(这与“值”之类的标签更相关)。 For example if 'id' is "lorem ispum dolor sit amet" it would output:例如,如果“id”是“lorem ispum dolor sit amet”,则为 output:
<input id="lorem" ipsum dolor sit amet />
Does anyone have a better way of conditionally including HTML attributes?有没有人有更好的方法来有条件地包含 HTML 属性? Note, I know I can use Rails HTML helpers like text_field_tag, but I'd like to find a solution without using those.注意,我知道我可以使用像 text_field_tag 这样的 Rails HTML 助手,但我想找到一个不使用它们的解决方案。
EDIT: I plan to do this with multiple HTML attributes (eg <input id="<%= id %>" value="<%= value %>" name="<%= name %>"... />编辑:我计划使用多个 HTML 属性(例如 <input id="<%= id %>" value="<%= value %>" name="<%= name %>"... />
You can use the full structure of the condition:您可以使用条件的完整结构:
<% unless id.blank? %>
<input id="<%= id %>" />
<% else %>
<input />
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.