问题
How does one embed ruby code in javascript for rails? I know you can do this easily in javascript responders for action methods (for e.g. in create.erb.js). But is there a way to do this for other custom javascript files that are included in the application using javascript_include_tag?
For e.g. in create.erb.js I can write code such as <%= if current_user_name ="xyz" %>
Is there a way to have this type of embedding in a custom js file such as custom.js that is used across the application and not just for generating a response for format.js.
Thanks,
Tabrez
回答1:
You can just create an _application.js.erb
file (name it whatever you wish) in the views/shared
folder and then include it in your application's layout file.
<%= render '/shared/application.js' %>
Make sure you wrap it in script
tags like normal and ensure that you use the DOM ready wrapper within that JS file like you normally would as well.
来源:https://stackoverflow.com/questions/8661366/can-you-use-embedded-ruby-in-custom-javascript-files-in-rails