我正在测试我的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标记之上/之前.