Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4, link in flash message is not parsed as HTML

In controller I have the following flash message:

flash[:notice] = %Q[Please #{view_context.link_to('create a new account', new_account_path)}, after that you will be able to create orders.].html_safe

Here is flash area in layout:

<div id="main_flash_area">
<% flash.each do |name, msg| %>
    <div class="alert text-center alert-info">
      <a class="close" data-dismiss="alert">&times; Закрыть</a>
      <%= msg %>
    </div>
<% end %>
</div>

It kinda renders into a link, but browser doesn't parse it as a link though. It is displayed as

Please <a href="/accounts/new">create a new account</a>, after that you will be able to create orders.

The generated HTML:

<div id="main_flash_area">
    <div class="alert text-center alert-info">
      <a class="close" data-dismiss="alert">× Закрыть</a>
      Please &lt;a href="/accounts/new"&gt;create a new account&lt;/a&gt;, after that you will be able to create orders.
    </div>
</div>

How do I make it a proper link? I guess it escapes < a> tag at some point.

like image 771
Extrapolator Avatar asked Jul 22 '14 12:07

Extrapolator


1 Answers

You need to sanitise your flash msg in the view.

<%= sanitize(msg) %>

This will render the link in the view rather than escaping the html.

Be aware that this will apply to all flash messages in your app. If you display any user input in the flash message you will have to remember to escape it before displaying it as Rails auto escaping will not apply.

Note the sanitize helper is less permissive that the raw helper and it can be configured. It works with links automatically, It removes script tags by default providing some protection if you have user content in your flash but you will need to do a full check to ensure you do not introduce any security issues. Check the Rails docs for more info.

like image 178
nmott Avatar answered Oct 03 '22 23:10

nmott