让模板和多个部分添加到布局中
首先,我要说我熟悉 content_for
。这并不是我真正要在这里寻找的东西。
我想允许一个模板和任意数量的部分来构建,比如说,我想要加载的 JavaScript 文件列表,并将它们传递到布局以供其处理并添加到 < /代码> 区域。我只想在页面确实需要它们时加载文件,所以我不想将它们全部放入布局中。它看起来也不像是由控制器处理的事情,因为这些主要是特定于视图的更改。
我尝试使用 content_for
返回名称数组,但这似乎不起作用。它也不允许多个部分将自己的先决条件添加到列表中。我还尝试在模板/部分中使用辅助函数来添加到列表,然后在布局中使用该列表,但布局代码似乎是在模板代码之前评估的。
有什么想法吗?顺便说一句,这不是特定于 JavaScript 的。我只需要一种将 Ruby 对象从模板/部分传递到布局的方法。
编辑:根据请求,一个示例。 css_import
只是我编写的一个模拟 CSS @import
的助手。
# In the layout
<style type="text/css">
<%- yield(:foobar).each do |foo| -%>
<%= css_import foo %>
<%- end -%>
</style>
# In the template
<%- content_for :foobar do
['layout', 'recipes', 'user']
end -%>
# The actual output from View -> Source
<style type="text/css">
</style>
First off, let me say that I am familiar with content_for
. It's not really what I'm looking for here.
I want to allow a template and any number of partials to build up, say, a list of JavaScript files I want to load, and pass them up to the layout for it to process and add to the <head>
area. I only want to load the files if the page actually needs them, so I'd rather not just put them all into the layout. Nor does it seem like something to be handled by the controller, because these are mainly view-specific changes.
I've tried using content_for
to return an array of names, but that doesn't seem to work. It also wouldn't allow for multiple partials to add their own prerequisites to the list. I've also tried using helper functions in the template/partials to add to a list, and then using that list in the layout, but it appears that the layout code is evaluated before the template code.
Any ideas? This isn't JavaScript-specific, by the way; I simply need a way to pass Ruby objects from the template/partials to the layout.
EDIT: Per request, an example. css_import
is just a helper I wrote that emulates a CSS @import
.
# In the layout
<style type="text/css">
<%- yield(:foobar).each do |foo| -%>
<%= css_import foo %>
<%- end -%>
</style>
# In the template
<%- content_for :foobar do
['layout', 'recipes', 'user']
end -%>
# The actual output from View -> Source
<style type="text/css">
</style>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许你应该看看 content_for 在做什么?它只是执行您分配给调用的块并将其存储在实例变量中。当使用正确的参数调用yield时,它会返回实例变量。
应该完全有可能创建您自己的两个帮助器方法来实现您的目标,例如:
您可以根据自己的喜好使这些函数变得奇特,例如当注册表仅包含 JavaScript 文件的位置时,您可以返回 HTML JavaScript include标签而不仅仅是文件路径。
Maybe you should have a look at what content_for is doing? It just executes the block you assigned to the call and stores it in an instance variable. When calling yield with the right parameter it return the instance variable.
It should be perfectly possible to create two helper methods of your own to accomplish your goal, for example:
You can make these functions as fancy as you like, for example when the registry contains only locations to JavaScript files, you can return HTML JavaScript include tags instead of just the file path.