gpt4 book ai didi

ruby-on-rails - Rails yield 和 content_for wieird 行为, `yield :filter` 仅在放置在默认 yield 之后才有效

转载 作者:行者123 更新时间:2023-12-05 06:14:13 28 4
gpt4 key购买 nike

假设我有这个部分,我正在尝试渲染

#layouts/_subheader.html.erb
<div class="subheader">
<%= yield %>
<%= yield :filters %>
</div>

当我在这样的 View 中使用这个部分时

<%= render 'layouts/sub_header' do %>
<h2> Content For Yield </h2>
<% content_for :filters do %>
<h2> Content for Filters </h2>
<% end %>
<% end %>

我得到的 HTML 输出为

<div class="subheader">
<h2> Content For Yield </h2>
<h2> Content for Filters </h2>
</div>

这按预期工作,但是当我更改部分中 yield 标签的顺序时出现问题

而不是上面的,如果我将部分重写为

#layouts/_subheader.html.erb
<div class="subheader">
<%= yield :filters %>
<%= yield %>
</div>

我得到输出为

<div class="subheader">
<h2> Content For Yield </h2>
</div>

未呈现 content_for :filters

我在这里做错了什么?这是正确的行为还是我做错了什么?

如果我必须让 yield :filters 的内容出现在普通 yield 之前,我该怎么办?

编辑:-

我试过了

#layouts/_subheader.html.erb
<div class="subheader">
<%= content_for :filters %>
<%= yield %>
</div>

但似乎效果不佳。

最佳答案

感谢 reddit 上的所有人和@Ezhil 我找到了解决方案,这就是我所做的

我所做的是像这样在渲染之前放置 content_for 捕获组

#index.html.erb
<% content_for :filters do %>
<h2> Content for Filters </h2>
<% end %>

<%= render 'layouts/sub_header' do %>
<h2> Content For Yield </h2>
<% end %>

在我的部分

#layouts/_subheader.html.erb 
<div class="subheader">
<%= content_for :filters %>
<%= yield %>
</div>

这是因为直到第一次 yield 才会执行该 block ,因此在该运行之前不会捕获任何内容。

关于ruby-on-rails - Rails yield 和 content_for wieird 行为, `yield :filter` 仅在放置在默认 yield 之后才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62981099/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com