how to include code into a js.erb view? in rails 3
-
07-07-2021 - |
Question
I have a website using unobtrusive ajax.
In short, the flow is:
- remote link
- Request managed by controller
- js.erb view sending response back to browser
I want all my js.erb views to execute similar "maintenance activity", like inserting flash messages when needed, updating the url, etc.
How can I make this DRY? Ideally, I would use a partial with the code to be executed every time but I couldn't find how to do this.
UPDATE 1: example
my js.erb file:
$("#challenge_actions").html("<%= escape_javascript(render partial: "challenges/best_practice_button")%>");
$("#flash_messages").html("<div id='flash_notice'><%= escape_javascript(flash[:notice])%></div>");
How can I extract the line with flash_messages and have it automatically included in all my js.erb files?
Thanks!
Solution
You can use js layouts , just like html layouts.
layouts/custom.js.erb
alert("<%=j flash[:notice] %>");
<%= yield %>
controllers/your_controller.rb
def your_action
flash[:notice] = "hello world"
@hello = "hello world"
respond_to do |format|
format.js { render layout: "custom" }
end
end
your_action.js.erb
alert("<%= j @hello %>");
OTHER TIPS
You can use the partial templates in erb as well, suppose you want to replace the content of the div with id "container", then assuming your are using jquery you can do
$('#container').html('<%= escape_javascript(render(:partial => 'mypartial'))%>')