Pregunta

Let's say I'm outputting a post title and in our database, it's Hello Y’all -- can I output it without using .html_safe, but in such a way that it doesn't get output in html as Hello Y’all?

That is, if a user copies a post title from a word processor that uses typographically correct apostrophes, I'm getting gibberish output since it's escaping the & in the database as &. Of course, I would want a title from the database that's Bonnie & Clyde to be output as Bonnie & Clyde since that is the correct HTML...

Is there a safe way to do this?

¿Fue útil?

Solución 2

SafeBuffer calls ERB::Util.h for strings that aren't html_safe, so you can gsub on ERB::Util.h(your_string) and replace instances of &[code] with &[code]; when first saving the string in your database. That way your string is first sanitized

The call you need is ERB::Util.h(your_string).gsub(/&(#x?[\da-fA-F]+;)/, '&\1')

Then whenever you need to display that particular string, call html_safe on it.

Otros consejos

Use ActionView::Helpers::SanitizeHelper

<%= "Hello Y&#8217;all" %>
<%= sanitize "Hello Y&#8217;all" %>

will produce:

Hello Y&#8217;all
Hello Y’all

there are 3 ways to do this:

1: "string".htmlsafe
2: <%= raw "string" %>
3. <%== "string" %>

I think you should use <%= raw "string" %> as it takes the argument, apply .to_s to it, and then it simply apply html_safe to it. Hence it would be safe to use 2nd option.

<%= raw "Y&amp;#8217;all" %> or <%== "Y&amp;#8217;all" %> are two possibilities.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top