我正在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)
<% content_for :navigation do %>
<ul>
<li>Home</li>
</ul>
<% end %>
他们说我读铁路指南http://guides.rubyonrails.org/layouts_and_rendering.html#using-方法的内容这应该行得通。但事实并非如此。我没有收到错误。看起来很简单,但我被难住了。
当我转到我的index.html.erb文件时,我希望看到这样的结果:
- 主页
我相信您想要的是拥有一个包含content_for
块的视图。因此,一个例子是,如果你有以下内容:
index.html.erb
<% content_for :head do %>
<%= stylesheet_link_tag 'users' %>
#Above this will load the users stylesheet
<% end %>
<h2>Example</h2>
<ul>
<% @users.each do |users| %>
<li><%= user.name %></li>
<% end %>
</ul>
然后,为了输出users
样式表中的内容,我们可以生成并传递content_for
的名称符号。
Application.html.erb
<!-DOCTYPE html>
<html>
<head>
<%= yield :head%>
<title>This is my title</title
</head>
<body>
<p>This is a test</p>
<%= yield %>
</html>
因此,回顾一下这里发生的事情,在我的例子中,我说我有一个users
样式表,我想将它加载到我的application.html.erb的<head></head>
中。为此,我设置了作为Rails助手的content_for
,并给它一个标识符sysmbol,即head
,然后在我执行yeild :head
的application.html.erb
中调用它。因此,我要让我的应用程序做的是,当该页面的index.html.erb
被呈现时,application.html.erb
将加载我的users
样式表。希望这能帮你解决问题。
更新解释
除此之外,将content_for
与yield
结合使用的目的是允许您从ANY视图将数据注入应用程序布局。作为另一个例子。你可以有以下几种:
<% content_for :title do %> My Title<% end %>
这里,当控制器渲染视图模板并将其与应用程序布局组合时,文本My title
将被替换。yield(:head)
可以方便地在需要时向特定页面添加更多元素。看看下面的例子:
app/views/layouts/application.html.erb
<% if content_for?(:navbar) %>
<%= yield(:navbar) %>
<% else %>
<%# default navbar %>
<section class="navbar"></section>
<% end %>
app/views/blah/index.html.erb
<% content_for(:navbar) do %>
<section class="navbar"></section>
<% end %>
另外需要注意的是,不确定您是如何开发应用程序或使用什么设计框架的,但您也可以查看Rails Bootstrap Navbar。也可能是另一种选择。
好吧,我想我有一个解决方案。您的代码:
<% content_for :navigation do %>
<ul>
<li>Home</li>
</ul>
<% end %>
应位于加载的文件的顶部。您的_header.html.erb是分部。如果您将此代码移动到视图/tasks/new.html.erb中,那么它将按预期工作。
然而,为了让它按您的意愿工作,您需要调整您的应用程序。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>
注意,我调用了不带=号的render-erb标记。这意味着我看不到头部分的内容,但它确实加载了。如果包含=符号,则它仍然有效,但也会呈现分部中可能包含的任何其他内容。注意:render标记必须位于yield标记之上/之前。