Rails 4,Flash 消息中的链接未解析为 HTML [英] Rails 4, link in flash message is not parsed as HTML
问题描述
在控制器中,我有以下闪现信息:
flash[:notice] = %Q[请#{view_context.link_to('create a new account', new_account_path)},之后就可以创建订单了].html_safe
这是布局中的闪存区域:
<% flash.each do |name, msg|%><div class="alert text-center alert-info"><a class="close" data-dismiss="alert">×Закрыть</a><%=味精%><%结束%>
它有点呈现为链接,但浏览器不会将其解析为链接.显示为
请<a href="/accounts/new">创建一个新帐户</a>,之后您就可以创建订单了.
生成的 HTML:
<div class="alert text-center alert-info"><a class="close" data-dismiss="alert">× Закрыть</a>请<a href="/accounts/new">创建一个新帐户</a>,之后您就可以创建订单了.
如何使它成为正确的链接?我想它逃脱了 <a> 在某个时候标记.
你需要在视图中sanitise
你的 flash msg
.
<%= sanitize(msg) %>
这将在视图中呈现链接而不是转义 html.
请注意,这将适用于您应用中的所有 Flash 消息.如果您在 flash 消息中显示任何用户输入,则必须记住在显示之前将其转义,因为 Rails 自动转义将不适用.
请注意,sanitize
助手不如 raw
助手那么宽松,并且可以对其进行配置.它自动处理链接,默认情况下会删除 script
标签,如果您的 Flash 中有用户内容,则提供一些保护,但您需要进行全面检查以确保不会引入任何安全问题.查看 Rails 文档了解更多信息.
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">× Закрыть</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 <a href="/accounts/new">create a new account</a>, 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.
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.
这篇关于Rails 4,Flash 消息中的链接未解析为 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!