问题描述
假设我需要在ERb模板的< head>
中调用一个JavaScript文件。 我的直觉是照常做的:
< head>
<%= javascript_include_tag:defaults%> <! - 例如 - >
< / head>
在我的应用程序的布局中。当然,这些JavaScript文件会被加载到我的应用程序的每个页面中,无论它们是否需要用于查看页面。
想知道是否有一种将JavaScript加载到头文件中的好方法,例如只在特定目录中找到的所有ERb模板。
我会使用。
例如,指定要在应用程序布局中插入的位置:
<头>
< title>圣诞快乐!< / title>
<%= yield(:head) - %>
< / head>
然后从视图发送:
<% - content_for(:head)do - %>
<%= javascript_include_tag:默认值 - %>
<% - end - %>
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>
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.
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.
I would use 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 -%>
这篇关于JavaScript在Rails应用程序中包含标记最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!