Re: Ruby variable that embeds html tags

Colin Law
Sat, 16 Jul 2011 11:07:58 -0000

On 15 July 2011 22:13, Jacob
<jacobkosman-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> This seems very simple, but I can''t quite get it. Probably because
I''m
> just starting out with RoR.
>
> My view has a slew of labels and text fields; many are
"required":
>
> <%= f.text_field :screen_name %> <span
class="required_field">Required
> field
>
> (The "required_field" class turns the text red and smaller.)
I''d like
> to not have everything between and sitting at
the end
> of every required line. I''d like instead to use a variable:
>
> <% req = "<span
class=''required_field''>Required field"
%>
>
> And then have
> <%= f.text_field :screen_name %> <%= req %>

By default Rails will assume that req may contain malicious text (such
as some evil js for example) and will escape it so that the raw html
appears on the page.  Since you know that req is safe to output
directly you can either use <%= req.html_safe %> or <%= req =
"<span
.... >".html_safe %>

On a separate point I would use a view helper method rather than
defining req inline however.

Colin

>
> Shorter and DRYer. But when I do that, I get my HTML printed to the
> screen, not interpreted.
>
> Help appreciated. Thanks!
> Jacob