gpt4 book ai didi

ruby-on-rails - 如何根据 Controller / Action 加载Javascript Assets ?

转载 作者:行者123 更新时间:2023-12-03 16:12:08 26 4
gpt4 key购买 nike

这是默认的application.js:

//= require jquery
//= require jquery_ujs
//= require_tree .

CoffeeScript模板具有以下内容:
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/

对我而言,“与此处匹配 Controller 有关的 ”是指foo_bar.js.coffee仅在使用foo_bar Controller 时加载。我对吗?

事实是,即使不需要它们,它也会加载所有Javascript文件。另外...我想知道如何根据 Controller 的 Action 有条件地包含Javascript文件。

最佳答案

有两种方法可以实现,这是我发现的最简单,最优雅的方法:

去除

//= require_tree .

指令,然后将模板更改为
<%= javascript_include_tag "application", controller_name %>

然后在应用程序中加载全局js,并在controller_name中加载特定于 Controller 的 Controller 。

例如,如果您在posts_controller中,则将加载posts.js或posts.js.coffee。

编辑

要执行此操作,您还可以添加
action_name

我建议的解决方案。您可能要考虑的一件事是将其分解为application_controller.rb:
before_filter :your_function

def your_function
@controller = controller_name
@action = action_name
end

然后像这样在您的布局中使用它
<%= javascript_include_tag "application", "#@controller.#@action" %>

关于ruby-on-rails - 如何根据 Controller / Action 加载Javascript Assets ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8468200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com