How to avoid the value returned by profitability

I recently had a problem returning the value returned by the yield in the template.

In my layout, I give a meta description so that I can define it from my template

<meta name="description" content="<%= yield :html_description %>" /> 

And here is my template, which unfortunately does not escape the value as expected:

 <% content_for :html_description, 'hello "you" guy' %> <meta name="description" content="hello "you" guy" /> 

I tried to avoid this with h () escaper, but it does not work:

 <meta name="description" content="<%= h(yield :html_description) %>" /> <meta name="description" content="hello "you" guy" /> 

I also tried with escape_once (), but it is too much:

 <meta name="description" content="<%= escape_once(yield :html_description) %>" /> <meta name="description" content="hello &amp;quot;you&amp;quot; guy" /> 

However, concatenating the return value with a string, it fixes the problem:

 <meta name="description" content="<%= '' + (yield :html_description) %>" /> <meta name="description" content="hello &quot;you&quot; guy" /> 

Does anyone understand this behavior?

Do you have a better solution than this concatenation that captures this by coincidence?

I am using Rails 2.3.8 - Thank you!

+6
yield html ruby-on-rails escaping
source share
3 answers

For self-closing tags, such as meta, img or br, you can use the "tag" method.

 <%= tag(:meta, :name => 'description', :content => yield(:html_description)) %> 

It gives you

 <meta content="&quot;I am surrounded by quotes&quot;" name="description" /> 
+6
source share

Function "h" only escapes invalid html. The problem with your code is that quotation marks are not invalid html. Otherwise, you will not be able to have quotes on your web page. "h" should do things like turn "<script>" in "& lt; script & gt;" instead of this.

so ... * wave hand * is not the method you are looking for.

What will probably solve this for you actually uses the rails methods to create the meta tag itself, and then the rails will nicely avoid it for you.

for example, if you tried the following:

 <%= content_tag(:meta, nil, :name => 'description', :content => yield(:html_description)) %> 

you will succeed:

 <meta content="hello &quot;you&quot; guy" name="description"></meta> 

Update:

Oh, and the reason the string concatenation does the trick is because newer versions of Rails will be html-safe, which it considers a dirty string ... however, you don't need this hack if you use the rail-based meta tag generation method.

+4
source share

You can use the raw () method to do something like this:

 <% microdata = "" %> <% microdata = "itemscope itemtype='#{yield :itemtype}'" if content_for? :itemtype %> <div class='container' <%= raw(microdata) %> > </div> 
0
source share

All Articles