Majiy
Majiy

Reputation: 1920

Rails: array.join with html in separator is escaped

I have an array of Strings containing unsave content (user input).

I want to join these Strings in my template, separated by <br />.

I tried:

somearray.join("<br />")

But this will also escape the sparator.

Is there a workaround, keeping in mind that the content of the array absolutely must be escaped?

Upvotes: 4

Views: 4862

Answers (4)

Kalsan
Kalsan

Reputation: 1039

Nowadays, the state-of-the-art way to solve this is:

# Inside a view:
safe_join(somearray, '<br />')

# From somewhere else, given the current controller:
controller.helpers.safe_join(somearray, '<br />')

Upvotes: 1

rep
rep

Reputation: 1784

raw and h provide ways to apply this default behavior selectively.

<%= raw user_values_array.map {|user_value| h user_value }.join('<br />') %>

Better still, Rails 3.1 introduced safe_join(array, sep) for this purpose. Used with html_safe it can do what you need.

<%= safe_join(user_values_array, "<br />".html_safe) %>

Documentation

Upvotes: 5

cicloon
cicloon

Reputation: 1099

Have you tried this?

raw somearray.join("<br />")

Upvotes: 2

Peter Brown
Peter Brown

Reputation: 51697

Is there a reason it has to be a <br /> tag? Could you use a list instead?

<ul>
  <% somearray.each do |item| %>
    <%= content_tag :li, item %>
  <% end %>
</ul>

Upvotes: 3

Related Questions