Question

I want to work DRYingly in the UJS and not repeat pieces of javascript

I also want to run specific js code depending on variables I get from the controller

so for example this could be the type of code in a ujs response

<% if !flash[:error].blank? %>
alert("there is an error! - <%= flash[:error] %>");
<% else %>
alert("nothing to see here, move along now.. <%= flash[:success] %>");
<% end %>

so I'd like to fire this code in a few ujs responses, but I don't know where to place it. Helper files are for html..

Where can I place such js/erb hybrid code so it can be reuseable - so I can call it from any .js.erb file?

Was it helpful?

Solution

You can render a partial from within your js.erb using the following syntax:

<%= render :partial => "shared/alerts" %>

Just put your code above into a partial in the appropriate directory. In my above example, the file would be called _alerts.js.erb and you'd put the partial in a directory I called shared (which would be in your views directory), but you can choose whatever directory you deem appropriate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top