Rails: Automatic inclusion of action/controller specific javascript files?

孤街浪徒 提交于 2019-12-12 15:03:20

问题


I am a beginner at rails development and moved from cakephp.

In cakephp there's something you can do in the layout to automatically include any javascript files that are named the same as either the controller or the action.

For instance in www.website.com/post/add

both post.js and post/add.js will automatically be loaded if they exist.

Is there a way to do this in rails? I tried doing a google but didn't know what to search for and didn't turn up much.

(Same thing with css)


回答1:


I'm not aware of this kind of functionality in rails, but you can simply do this in a layout:

javascript_include_tag "#{controller.controller_name}"
javascript_include_tag "#{controller.action_name}"

it will not check if the file exists, so you can go further and create application helper, and move there a logic of js including and checking if file exists:

def include_controller_js
 javascript_include_tag "#{controller.controller_name}" if File.exists?("#{Rails.root}/public/javascripts/#{controller_name}.js")
end

But since rails 3.1 there is an asset pipeline with application.js manifest file, so maybe you would like to read more about it.



来源:https://stackoverflow.com/questions/8249946/rails-automatic-inclusion-of-action-controller-specific-javascript-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!