我有application.html.erb
,有这个:
<!-- Truncated for Brevity -->
<body>
<%= content_for?(:content) ? yield(:content) : yield %>
</body>
然后我有另一个布局family_tree.html.erb
看起来像这样:
<%= render template: "layouts/application" %>
<main id="view">
<title>Timeline!</title>
<%= render partial: "tree_header" %>
<% content_for :content do %>
<%= yield %>
<% end %>
</main>
部分_tree_header.html.erb
看起来像这样:
<header class="profile-header">
<div class="wrapper">
<div class="profile-author">
<h2 class="center author-name">Martha Doe <a class="author-description-btn" href=""><i class="icon-list-2"></i></a></h2>
<h4 class="author-title">Aunt <i class="author-title-circ"></i><i class="author-title-circ"></i><i class="author-title-circ"></i></h4>
<!-- <div class="author-description">
<p>Nullam quis risus eget urna mollis ornare vel eu leo. Etiam porta sem malesuada magna mollis euismod.</p>
</div> -->
</div>
<nav class="profile-nav center">
<ul>
<li><%= link_to "Timeline", timeline_path %></li>
<li class="active"><a href="#">Family Tree</a></li>
</ul>
</nav>
</div>
</header>
这就是我想要它呈现的方式(这是静态HTML):
但这就是它呈现的方式:
请注意,即使我在render partial: "tree_header"
块中的yield
语句之前指定了content_for
,但在我layouts/family_tree.html.erb
内的收益后,它似乎仍然呈现。< / p>
我该如何解决这个问题?
修改1
使用amihule的答案我或多或少地解决了它,但现在我看到顶部和tree_header
部分之间的空格。这个content_for
块可能导致这个空间吗?
答案 0 :(得分:2)
TL; DR:将<%= render template: "layouts/application" %>
移至子布局的底部,并在content_for
块中包含其他所有内容。
<% content_for :content do %>
<main id="view">
<title>Timeline!</title>
<%= render partial: "tree_header" %>
<%= yield %>
</main>
<% end %>
<%= render template: "layouts/application" %>
您希望首先填写:content
的内容,然后渲染模板以包含此内容。您设置模板的方式,您将在rails控制台上注意到它在您的部分之前呈现layouts/application
,如下所示:
Rendered test/foo.html.erb within layouts/family_tree
Rendered layouts/application.html.erb
Rendered test/_tree_header.html.erb
答案 1 :(得分:1)
<强> TL; DR 强>
amiuhle的回答:将// SomethingID keeps its value (greater than 0):
@Html.DropDownListFor(m => m.SomethingID, Model.SomethingList)
放在content_for :content do
文件的顶部。
<强>解释强>
您的代码按顺序执行。让我们看看会发生什么
your_controller.rb
family_tree.html.erb
该操作将首先调用class YourController < ApplicationController
def show
...
render layout: "family_tree"
end
布局,其第一行是
family_tree.html.erb
因此它将直接调用主application.html.erb
<%= render template: "layouts/application" %>
此时,没有定义<!-- Truncated for Brevity -->
<body>
<%= content_for?(:content) ? yield(:content) : yield %>
</body>
,所以它只会让节目正常!然后它会从content_for(:content)
family_tree
正如@amiuhle所解释的那样,这是因为你在检查后设置了content_for(:content)。解决方案是将<main id="view">
<title>Timeline!</title>
<%= render partial: "tree_header" %>
<!-- The below piece of code is absolutely useless as it is not used afterwards -->
<% content_for :content do %>
<%= yield %>
<% end %>
</main>
放在content_for :content do
文件的顶部。