Rails-覆盖 在使用部分或特定控制器视图时的页面元素

问题描述 投票:9回答:1

是否有办法在Rails视图内追加或覆盖<head>页面元素?

假设我只想在特定视图的<head>中包含一些内容,并且我正在使用application.html.erb来呈现其余视图。在这种情况下,我不想丢弃application.html.erb,而只是将其附加到一个特定页面的head元素,别无其他。

ruby-on-rails erb ruby-on-rails-3.2
1个回答
31
投票

在您的application.html.erb中:

<head>
  <% if content_for? :for_head %>
    <%= yield :for_head %>
  <% end %>
</head>

在您的“特定”视图中:

<% content_for :for_head do %>
  Something-to-put-in-head
<% end %>

:for_head未预定义:命名取决于您。可能是任何东西。

© www.soinside.com 2019 - 2024. All rights reserved.