3

In my view I want to display some right double angle quotes in my link.

Before Rails 3, this worked:

<%= link_to "&raquo; #{@category.name}", some_path %>

Now what should I do if I want to specify the &raquo; as html_safe but not the rest of the link's text?

In other words I do not want to do this:

<%= link_to "&raquo; #{@category.name}".html_safe, some_path %> I do not want the @category.name treated as html_safe.

This produces the desired result:

<%= link_to "&raquo;".html_safe + " #{@category.name}", some_path %>

However, if I do this:

<%= link_to "#{@category.name}" + "&raquo;".html_safe, some_path %>

The output of the angle quotes is not treated as safe. I see &raquo; on my page and not ».

Why?

I tried extracting "&raquo;".html_safe to a helper method with the same results.

Is there a way to easily designate hard coded text/symbols as HMTL safe in Rails 3?

Thanks.

johnnycakes
  • 2,440
  • 2
  • 28
  • 36

2 Answers2

3

In this situation I often explicitly escape the unsafe part:

"&raquo; #{h @category.name}".html_safe
Michaël Witrant
  • 7,525
  • 40
  • 44
  • I would remove the "often" bit here, or replace it with always, or indicate that sanitizer could be used as well. – Bert Goethals Jun 02 '11 at 02:40
  • h explicitly escapes html. See [html_escape](http://api.rubyonrails.org/classes/ERB/Util.html#method-c-html_escape). – Jonathan Tran Jun 02 '11 at 03:38
  • It looks like this is the right answer...but I don't like it. I wish there was a way to specify a list of characters/html as "ok", or at least a way for hard coded characters/html/symbols in views to be trusted. – johnnycakes Jun 03 '11 at 20:48
0

you need to make sure that the whole string is html_safe...

I'd recommend to try this:

   "&raquo; #{h @cagegory.name}".html_safe
Tilo
  • 33,354
  • 5
  • 79
  • 106
  • This is dangerous. Note that the category name is not treated safely, and the system becomes vulnerable to JS injection. – Bert Goethals Jun 02 '11 at 02:39
  • good point! yes, if name is a user accessible attribute, then we need an "h" before the category name to escape HTML! (I'll add that) – Tilo Jun 02 '11 at 05:06