I am building a block of HTML code using Rails' content_tag
helper. The challenge I face right now is joining HTML strings from an array with HTML elements generated by content_tag
.
RuboCop Rails/OutputSafety reference.
For example:
options = ["<li>Three</li>", "<li>Four</li>", "<li>Five</li>"]
# This is code to generate blocks of HTML
out = []
out << content_tag(:ul,
content_tag(:li, "One") +
content_tag(:li, "Two") +
options.join(''),
:class => ["class_1", "class_2"])
safe_join(out)
# Expect result should be like
<ul class="class_1 class_2">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
# Actual result
<ul class="class_1 class_2">
<li>One</li>
<li>Two</li>
"<li>Three</li><li>Four</li><li>Five</li>"
</ul>
However, if I use the html_safe approach like below, it will work.
%{<ul>
<li>One</li>
<li>Two</li>
#{options.join('')}
</ul>
}.html_safe
Any suggestions on what I should change?
# New apporach
options = ["Three", "Four", "Five"]
out = []
out << content_tag(:ul,
content_tag(:li, "One") +
content_tag(:li, "Two") +
options.collect do |option|
content_tag(:li, "#{option[0]}")
end.join(""),
:class => ["class_1", "class_2"])
safe_join(out)
# New approach result
<ul class="class_1 class_2">
<li>One</li>
<li>Two</li>
"<li>Three</li><li>Four</li><li>Five</li>"
</ul>