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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 如何使用content_for以便内容显示在布局中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在测试我的rails 3.2应用程序中的content_for并遵循rails指南,但它们是特定于实际文件的,我似乎无法获得收益:

application.html.erb文件

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. ...
  5. </head>
  6.  
  7. <body>
  8.  
  9.  
  10.  
  11.  
  12. <%= yield :navigation %> #shouldn't this load the content_for block named :navigation specified in the _main_nav.html.erb partial?
  13.  
  14. <%= yield %> #this load the index page content
  15.  
  16.  
  17. </body>
  18. </html>

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

  1. <% content_for :navigation do %>
  2. <ul>
  3. <li>Home</li>
  4. </ul>
  5.  
  6. <% end %>

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

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

>家

解决方法

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

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

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

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

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

猜你在找的Ruby相关文章