【问题标题】:Adding content to a layout from a partial从部分向布局添加内容
【发布时间】:2009-08-29 20:46:51
【问题描述】:

假设我有一个应用程序布局,并且我在他们的 :head 内容中生成如下:

<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title></title>
    <%= stylesheet_link_tag 'scaffold' %>
    <%= yield(:head) %>
</head>

假设在同一个应用程序布局中,我调用部分来呈现主菜单。

<body>

    <p style="color: green"><%= flash[:notice] %></p>

    <!-- Main Menu -->
    <%= render :partial => 'menu/menu_main' %>
</body>

有什么方法可以从我的 _menu_main.erb 部分中将内容添加到我的应用程序布局的 :head 部分(比如添加一些 css)?

【问题讨论】:

    标签: ruby-on-rails layout


    【解决方案1】:

    您必须使用 content_for 标签。

    <% content_for :head do -%>
      *your code here*
    <% end -%>
    

    因此,您放入的代码将出现在 html 文件的 head 上。

    这个 railscasts 剧集更详细地解释了它:http://railscasts.com/episodes/8-layouts-and-content-for

    【讨论】:

      【解决方案2】:

      这是答案https://stackoverflow.com/a/10226010

      在你的application.html.erb

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

      在您的“特定”视图中:

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

      :for_head 未预定义:命名由您决定。可以是任何东西。

      【讨论】:

        猜你喜欢
        • 2012-08-11
        • 1970-01-01
        • 2018-08-14
        • 2020-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多