问题
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