在Rails中包含特定于页面的JavaScript的正确方法 [英] The right way to include page-specific JavaScript in Rails

查看:57
本文介绍了在Rails中包含特定于页面的JavaScript的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包括这个,例如:

  jQuery(document).ready(function($){
$('#my-modal')。modal(options)
});

在rails应用中的一个特定位置。在我的例子中,该文件名为views / modals / mymodal.html.erb。那里只有那里。



如果不把它放在所有页面上,如果我把它放在资产中,我就无法弄清楚如何做到这一点。

解决方案

这些是一些有用的技巧



#1,文件为js




  • 为您的javascript创建文件 your.js

  • 关于特定布局的调用文件 your.js

  • 删除 // = require_tree。 on application.js

  • your.js 添加到资产percompile config / application.rb config.assets.precompile + =%w(your.js)






#2放入特定文件非布局(不推荐)



将带有javascript标签的js脚本放在 mymodal.html.erb






#3使用if..else ..



将你的js脚本放入 layout / yourlayout.html .erb 并使用 i f .. else .. 逻辑。



例如:


 < %if current_page?(yourspecific_path)%> 
< script language =text / javascript>
你的javascript在这里..
< / script>
<%end%>


阅读更多这里关于 current_page?



或使用 request.fullpath 获取当前的完整路径



示例:


 <%if request.fullpath == yourspecific_path%> 
< script language =text / javascript>
你的javascript在这里..
< / script>
<%end%>


阅读更多这里关于 request.fullpath



如果您希望脚本放入文件 .js <,您也可以合并#1和#3 / p>

欢呼


I want to include this, for example:

jQuery(document).ready(function($) {
    $('#my-modal').modal(options)
});

In one specific place in a rails app. In my case the file is called views/modals/mymodal.html.erb. There and only there.

I can't figure out how to do that without getting it on all pages as would happen if I put it in assets.

解决方案

These are some useful tricks

#1 with file js

  • Create file your.js for your javascript
  • call file your.js on specific your layout
  • remove //= require_tree . on application.js
  • add your.js to asset percompile on config/application.rb : config.assets.precompile += %w( your.js )

#2 put into specific file non layout (not recommended)

put your js script with javascript tag on mymodal.html.erb


#3 use if..else..

put your js script into layout/yourlayout.html.erb and use if.. else.. logic.

example :

 <% if current_page?(yourspecific_path) %>
  <script language="text/javascript">
   your javascript here ..
  </script>
 <% end %>

Read more here about current_page?

Or use request.fullpath to get current full path

example :

 <% if request.fullpath == yourspecific_path %>
  <script language="text/javascript">
   your javascript here ..
  </script>
 <% end %>

Read more here about request.fullpath

Also you can combine #1 and #3 if you want script put into file .js

cheers

这篇关于在Rails中包含特定于页面的JavaScript的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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