Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - wrap HTML element around text of link_to() in ruby code without disabling all escaping

Tags:

This is pretty basic but I'm not having any luck finding anything in the Rails documentation. There is a view helper method (Ruby code, not HAML) that returns

link_to(user_controlled_text, destination, options)

and I need to wrap an HTML element (namely <bdi>) around the user_controlled_text. If I do

link_to("<bdi>#{user_controlled_text}</bdi>", ...)

then my element is treated as part of the user-controlled text to be escaped. Fair enough. How do I tell Rails not to escape the <bdi> and </bdi> but still escape the user_controlled_text?

like image 365
zwol Avatar asked Feb 27 '18 18:02

zwol


2 Answers

Use content_tag:

link_to(content_tag(:bdi, user_controlled_text), destination)

# or with a block
link_to(destination) do
  content_tag(:bdi, user_controlled_text)
end
like image 188
max Avatar answered Sep 17 '22 05:09

max


Try link_to("<bdi>#{h user_controlled_text}</bdi>".html_safe, ...).

If the h doesn't work, use ERB::Util::h.

like image 42
Phlip Avatar answered Sep 20 '22 05:09

Phlip