加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 如何使用content_for以便内容显示在布局中

发布时间:2020-12-17 04:30:01 所属栏目:百科 来源:网络整理
导读:我正在测试我的rails 3.2应用程序中的content_for并遵循rails指南,但它们是特定于实际文件的,我似乎无法获得收益: application.html.erb文件: !DOCTYPE html htmlhead .../headbody%= yield :navigation % #shouldn't this load the content_for block nam
我正在测试我的rails 3.2应用程序中的content_for并遵循rails指南,但它们是特定于实际文件的,我似乎无法获得收益:

application.html.erb文件:

<!DOCTYPE html>
 <html>
<head>
 ...
</head>

<body>




<%= yield :navigation %> #shouldn't this load the content_for block named :navigation specified in the _main_nav.html.erb partial? 

 <%= yield %>  #this load the index page content


</body>
 </html>

我创建了一个布局文件_main_nav.html.erb(我知道我可以使用<%= render'layouts / header'%>进行渲染,但我尝试使用content_for)_main_nav.html.erb是:

<% content_for :navigation do %>
<ul>
 <li>Home</li>
 </ul>

<% end %>

他们是我阅读RailsGuide http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method的方式
这应该工作.但事实并非如此.我没有收到错误.看似简单,但我很难过.

当我转到我的index.html.erb文件时,我希望看到这个结果:

>家

解决方法

好的,我想我有一个解决方案.你的代码:
<% content_for :navigation do %>
<ul>
<li>Home</li>
</ul>
<% end %>

应该位于正在加载的文件的顶部.你的_header.html.erb是部分的.如果您将此代码移动到views / tasks / new.html.erb中,那么它将按预期工作.

但是,为了使其按您的需要工作,您需要调整application.html.erb文件:

<p>this is where we should see the "Home" link appear that is defined in _header.html.erb:</p>
<section class="header">
<% render 'layouts/header' %>
<%= yield :navigation %>
</section>

请注意,我在没有=符号的情况下调用了渲染erb标记.这意味着我没有看到标题的内容部分,但它确实加载.如果您包含=符号,那么它仍然有效,但也会呈现您在部分中可能拥有的任何其他内容.注意:render标记必须位于yield标记之上/之前.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读