简体   繁体   English

如何在视图文件夹中包含js.erb文件

[英]How to include js.erb file in view folder

I have a JavaScript file to use with a view. 我有一个用于视图的JavaScript文件。 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. 需要有Ruby代码,我需要在Ruby中进行render ,所以我理解我不能将JavaScript文件放在资产管道中。 I can put it in the same view folder as the .html.erb file. 我可以把它放在与.html.erb文件相同的视图文件夹中。

How do I include the JavaScript file, or use that JavaScript file for that view file? 如何包含JavaScript文件,或将该JavaScript文件用于该视图文件? 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 (显然使用了资产管道),使用脚本src="myfile.js"作为myfile.js.erb文件(但找不到myfile.js ),并命名我的js.erb file( users.js.erb )与我的.html.erb文件( users.html.erb )相同,但都无济于事。

javascript_include_tag won't work js.erb declared in the view folder itself. javascript_include_tag将无法在视图文件夹本身中声明的js.erb工作。 There are three different ways you can have the javascript. 有三种不同的方法可以使用javascript。

1] Write the code in the view, ie, in the html.erb itself. 1]在视图中编写代码,即在html.erb本身。

2] Create js file in public/javascripts folder and include it using javascript_include_tag. 2]在public / javascripts文件夹中创建js文件,并使用javascript_include_tag包含它。

3] In case you want to make the request as Ajax: 3]如果您想以Ajax的形式提出请求:

  • Create the js.erb in the view folder itself with the same name as that of the action. 在视图文件夹本身中创建js.erb,其名称与操作的名称相同。
  • In the view where some form is created which will be calling this action, make the request using :remote => true . 在创建某个将调用此操作的表单的视图中,使用以下命令发出请求:remote => true
  • In the called action, use code as follows: 在被调用的操作中,使用代码如下:

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

you can do this by 你可以做到这一点

render :partial => "myfile"

you have to keep your file in controller's view directory with name _myfile.js.erb 您必须将文件保存在控制器的视图目录中,名称为_myfile.js.erb

Now you can write your own code (js,ruby) here and probably can separate out js with javascript_include_tag to avail asset pipline 现在你可以在这里编写你自己的代码(js,ruby),并且可能可以用javascript_include_tag将js分开以利用资产pipline

This file will be first rendered by erb engine and then as javascript. 该文件将首先由erb引擎呈现,然后作为javascript呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM