如何在视图文件夹中包含js.erb文件 [英] How to include js.erb file in view folder

查看:62
本文介绍了如何在视图文件夹中包含js.erb文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于视图的JavaScript文件。需要有Ruby代码,我需要在Ruby中执行 render ,所以我知道我不能将JavaScript文件放在资产管道中。我可以将它放在与 .html.erb 文件相同的视图文件夹中。

I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do render in Ruby, so I understand that I can't put the JavaScript file in the asset pipeline. I can put it in the same view folder as the .html.erb file.

如何包含JavaScript文件,或者为该视图文件使用该JavaScript文件?我在我的视图中尝试了 javascript_include_tag (显然使用了资产管道),使用脚本 src =myfile.js对于 myfile.js.erb 文件(但找不到 myfile.js ),并命名为 js.erb 文件( users.js.erb )与我的 .html.erb相同文件( users.html.erb ),但都无济于事。

How do I include the JavaScript file, or use that JavaScript file for that view file? I tried javascript_include_tag in my view (that uses the asset pipeline apparently), using script src="myfile.js" for the myfile.js.erb file (but it can't find myfile.js), and names my js.erb file (users.js.erb) the same as my .html.erb file (users.html.erb), but all to no avail.

推荐答案

javascript_include_tag将无法在视图文件夹本身中声明的js.erb工作。有三种不同的方法可以使用javascript。

javascript_include_tag won't work js.erb declared in the view folder itself. There are three different ways you can have the javascript.

1]在视图中编写代码,即在html.erb本身。

1] Write the code in the view, i.e., in the html.erb itself.

2]在public / javascripts文件夹中创建js文件并使用javascript_include_tag包含它。

2] Create js file in public/javascripts folder and include it using javascript_include_tag.

3]如果你想提出请求作为Ajax:

3] In case you want to make the request as Ajax:


  • 在视图文件夹中创建js.erb,其名称与操作名称相同。

  • 在创建一些将调用此操作的表单的视图中,使用创建请求:remote => true

  • 在被调用的操作中,使用如下代码:

  • Create the js.erb in the view folder itself with the same name as that of the action.
  • In the view where some form is created which will be calling this action, make the request using :remote => true.
  • In the called action, use code as follows:

def action
  respond_to do |format|
    format.js
  end
end


这篇关于如何在视图文件夹中包含js.erb文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆