• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Rails 3.1 资产管道:加载特定于控制器的脚本?

用户头像
it1352
帮助3

问题说明

如果我在 Rails 3.1 中生成一个新的控制器,也会自动添加一个带有控制器名称的 javascript 文件.首先,我认为这个javascript文件只会在调用相关控制器时使用.

If I generate a new controller in Rails 3.1, also a javascript file with the name of the controller will added automatically. Firstly, I thought this javascript file will used only, when the related controller is called.

默认情况下,application.js 文件中有 //= require_tree . 指令,其中包含其树上的每个 javascript 文件.

By default there is the instruction //= require_tree . in the application.js-file, that include every javascript file on it's tree.

如何只加载控制器特定的脚本?

How could I load only the controller specific script?

正确答案

#1

只加载必要的 name_of_the_js_file.js 文件:

To load only the necessary name_of_the_js_file.js file:

  1. application.js

将您的 js 文件(您希望在加载特定页面时加载)保留在资产管道中

keep your js file (that you want to load when a specific page is loaded) in the asset pipeline

application_helper.rb

def javascript(*files)
  content_for(:head) { javascript_include_tag(*files) }
end
  • 屈服于您的布局:

  • yield into your layout:

    <%= yield(:head) %>
    
  • 在您的视图文件中添加:

  • add this in your view file:

    <% javascript 'name_of_the_js_file' %>
    

那应该没问题

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcbbkkg
系列文章
更多 icon
同类精品
更多 icon
继续加载