Rails:使用“content_for”在相应的“产量”之后内部布局
我想这个问题以前已经被问过,但尽管我搜索了谷歌,但我还没有找到解决方案。
这就是我在 Rails 2.3.5 中尝试做的事情:
layouts/application.html.erb:
<html>
<head>
... some other stuff
<%= yield :head %>
</head>
<body>
<% content_for :head, "something that belongs in the head" %>
</body>
</html>
注意 content_for 之前的产量。
我知道Rails - 默认情况下 - 不允许在使用yield 之后定义 :head 的内容 - 这是有道理的。
我什至尝试挂钩模板渲染过程,但到目前为止没有成功。
所以我的目标是能够在部分/模板中定义 content_for ,并在响应发送到浏览器之前以某种方式延迟并执行“yield”。
有人想出解决方案吗?
问候和感谢, 弗兰克
更新 我将采用 weppos 的想法并尝试使用机架中间件。谢谢
I think this has been asked before but even though I searched Google I haven't come up with a solution.
So this is what I'm trying to do in Rails 2.3.5:
layouts/application.html.erb:
<html>
<head>
... some other stuff
<%= yield :head %>
</head>
<body>
<% content_for :head, "something that belongs in the head" %>
</body>
</html>
Notice the yield before the content_for.
I know that Rails - by default - doesn't allow the content of :head to be defined after yield has been used - makes sense.
I even tried hooking into the template render process but no success so far.
So my goal is to be able to define content_for inside partials/templates and have the "yield" somehow delayed and executed just before the response is send to the browser.
Has somebody come up with a solution?
Greetings and thanks,
Frank
Update
I'll go with weppos's idea and try myself on rack middleware. thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
渲染过程首先加载并执行操作模板,然后用选定的布局装饰模板。
布局是从上到下渲染的,因此在
:head
渲染完成后,您无法向:head
添加更多内容。你需要改变你的策略。要么将片段放入部分并将其附加到操作视图,要么使用后处理策略(例如 Rack 模块/after_filter)直接更改 html 代码。
我可能会根据我的实际需要尝试找到更好的解决方案。如果您遇到此问题,则错误很可能是在其他地方,可能是在应用程序架构中。
The rendering process first loads and executes the action template, then decorates the template with the selected layout.
The layout is rendered from top to botton, thus you can't add more content to
:head
after:head
is already rendered.You need to change your strategy. Either place the fragment in a partial and attach it to your action views or use a post-processing strategy such as a Rack module/after_filter to alter the html code directly.
I probably would try to find a better solution based on what I actually need. If you are encountering this issue, chances are the error is somewhere else, perhaps in the app architecture.
content_for
语句中不应有等号。它应该是:如果您在模板和部分中定义内容,那么它应该可以工作。 Railscast 第 8 集 介绍了此技术。
There shouldn't be an equals sign in your
content_for
statement. It should be:If you define the content within your templates and partials then it should work. This technique was covered in Railscast episode 8.