Javascript Include Tag Best Practice in a Rails Application(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 -%>
这篇关于Javascript 在 Rails 应用程序中包含标签最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript 在 Rails 应用程序中包含标签最佳实践


基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01