Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one NOT html_encode a variable in rails?

With Rails, If I have a variable with HTML content, how do I output it, unencoded in my view file?

This code, for example:

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= my_variable %>

Outputs:

&lt;b&gt;Some Bolded Text&lt;/b&gt;
like image 575
deadkarma Avatar asked Mar 30 '10 01:03

deadkarma


People also ask

How do you encode a string in Ruby?

Ruby has the method Encoding. default_external which defines what the current operating systems default encoding is. Ruby defaults to UTF-8 as its encoding so if it is opening up files from the operating system and the default is different from UTF-8, it will transcode the input from that encoding to UTF-8.

What is partials in Rails?

A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.


1 Answers

Are you using Rails 3 Beta? Rails 2 by default does not HTML escape your output, you usually have to use the h helper, see Nate's post. If you are using Rails 3 you need to either use the raw helper or set your string as html safe. Examples

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= raw my_variable %>

Or

<% my_variable = "<b>Some Bolded Text</b>".html_safe %>
<%= my_variable %>   

Check your Rails version and get back to us.

like image 112
scottd Avatar answered Oct 13 '22 21:10

scottd