I have
@str = "<b>Hi</b>"
and in my erb view:
<%= @str %>
What will display on the page is: <b>Hi</b>
when what I really want is Hi. What's the ruby way to "interpret" a string as HTML markup?
Edit: the case where
@str = "<span class=\"classname\">hello</span>"
If in my view I do
<%raw @str %>
The HTML source code is <span class=\"classname\">hello</span
> where what I really want is <span class="classname">hello</span>
(without the backslashes that were escaping the double quotes). What's the best way to "unescape" those double quotes?
This question is related to
html
ruby-on-rails
ruby
string
@str = "<span class=\"classname\">hello</span>"
If in my view I do
<%raw @str %>
The HTML source code is<span class=\"classname\">hello</span>
where what I really want is<span class="classname">hello</span>
(without the backslashes that were escaping the double >quotes). What's the best way to "unescape" those double quotes?
Solution: use double quotes inside of single quotes (or single inside of double) to avoid escaping with a backslash.
@str = '<span class="classname">hello</span>'
<%raw @str %>
The html_safe version works well in Rails 4...
<%= "<center style=\"color: green; font-size: 1.1em\" > Administrators only </center>".html_safe if current_user.admin? %
>
since you are translating, and picking out your wanted code from a person's crappy coded file, could you use content_tag, in combo with your regex's.
Stealing from the api docs, you could interpolate this translated code into a content_tag
like:
<%= content_tag translated_tag_type.to_sym, :class => "#{translated_class}" do -%>
<%= translated_text %>
<% end -%>
# => <div class="strong">Hello world!</div>
Not knowing your code, this kind of thinking will make sure your translated code is too compliant.
You can also use simple_format(@str)
which removes malicious code. Read more here: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Or you can try CGI.unescapeHTML method.
CGI.unescapeHTML "<p>This is a Paragraph.</p>"
=> "<p>This is a Paragraph.</p>"
You are mixing your business logic with your content. Instead, I'd recommend sending the data to your page and then using something like JQuery to place the data where you need it to go.
This has the advantage of keeping all your HTML in the HTML pages where it belongs so your web designers can modify the HTML later without having to pour through server side code.
Or if you're not wanting to use JavaScript, you could try this:
@str = "Hi"
<b><%= @str ></b>
At least this way your HTML is in the HTML page where it belongs.
Source: Stackoverflow.com