mardi 5 septembre 2017

Join HTML string from Array on nested content_tag

I am building a block of HTML code using Rails content_tag helper and I do know how to generate nested blocks of HTML. The only challenge I face right now is how to join HTML string from an array with HTML elements generated by content_tag.

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?

Aucun commentaire:

Enregistrer un commentaire