【问题标题】:Rails 4, link in flash message is not parsed as HTMLRails 4,Flash 消息中的链接未解析为 HTML
【发布时间】:2014-07-22 12:45:48
【问题描述】:

在控制器中,我有以下闪烁消息:

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

这是布局中的闪存区域:

<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>

它有点呈现为链接,但浏览器不会将其解析为链接。它显示为

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

生成的 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>

如何使它成为正确的链接?我猜它在某些时候会转义 标记。

【问题讨论】:

标签: html ruby-on-rails-4 escaping


【解决方案1】:

你需要在视图中sanitise你的闪光灯msg

&lt;%= sanitize(msg) %&gt;

这将在视图中呈现链接,而不是转义 html。

请注意,这将适用于您应用中的所有 Flash 消息。如果您在 flash 消息中显示任何用户输入,则必须记住在显示之前先对其进行转义,因为 Rails 自动转义将不适用。

请注意,sanitize 助手比 raw 助手更宽松,并且可以配置。它自动与链接一起工作,默认情况下它会删除script 标签,如果您的闪存中有用户内容,它会提供一些保护,但您需要进行全面检查以确保您不会引入任何安全问题。查看 Rails 文档了解更多信息。

【讨论】:

  • 太好了,正是我需要的!
  • 有什么方法可以在不清除所有闪存消息的情况下做到这一点?
【解决方案2】:

非常感谢您的解决方案 nmott。

这里为未来的读者提供了更多背景信息,包括您的解决方案,因为我不明白如何使用它。

在 views/layout/application.html.erb 中,注意 sanitize(msg) 以呈现 html。

<body>
   <%= render 'layouts/header' %>
  <div class="container">
  <% flash.each do |name, msg| %>
  <%= content_tag(:div, sanitize(msg), class: "alert alert-info") %>
<% end %>
<%= yield %>
</div>
</body>

要使其适用于更新,请在 controllers/your_model_controller.rb 中:

def update
    respond_to do |format|
      if @review.update(review_params)
        format.html { redirect_to @item, notice: "Review was successfully updated. #{view_context.link_to("review", item_review_path(@review.item, @review))}" }
        format.json { render :show, status: :ok, location: @item }
      else
        format.html { render :edit }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多