4

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?

Gareth
  • 133,157
  • 36
  • 148
  • 157
Majiy
  • 1,890
  • 2
  • 24
  • 32

4 Answers4

4

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

rep
  • 1,546
  • 1
  • 12
  • 19
  • 1
    Also you can use the `tag` helper, like this: `safe_join(somearray.split('\\n'), tag(:br))` – amoebe Oct 30 '17 at 13:52
3

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>
Peter Brown
  • 50,956
  • 18
  • 113
  • 146
2

Have you tried this?

raw somearray.join("<br />")
cicloon
  • 1,099
  • 5
  • 13
0

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 />')
Kalsan
  • 822
  • 1
  • 8
  • 19