Javascript 在 Rails 应用程序中包含标签最佳实践
假设我需要在 ERb 模板的 <head>
中调用一个 javascript 文件.我的直觉是照常行事:
Say I need to call a javascript file in the <head>
of an ERb template.
My instinct is to do the usual:
<head>
<%= javascript_include_tag :defaults %> <!-- For example -->
</head>
在我的应用程序布局中.问题当然是这些 javascript 文件被加载到我的应用程序中的每个页面中,无论正在查看的页面是否需要它们.
in my application's layout. The problem of course becoming that these javascript files are loaded into every page in my application, regardless of whether or not they are needed for the page being viewed.
所以我想知道是否有一种很好的方法可以将 javascript 加载到例如仅在特定目录中找到的所有 ERb 模板的标头中.
So what I'm wondering is if there's a good way of loading a javascript into the the headers of, for example, all ERb templates found only in a specific directory.
推荐答案
我会使用 content_for.
例如,指定将其插入应用程序布局的位置:
For instance, specify the place to insert it in the application layout:
<head>
<title>Merry Christmas!</title>
<%= yield(:head) -%>
</head>
然后从视图发送到那里:
And send it there from a view:
<%- content_for(:head) do -%>
<%= javascript_include_tag :defaults -%>
<%- end -%>
相关文章