JavaScript templates – Minus Mor plugin

First we need to install plugin:

cd  rails_app_directory
./script/plugin install http://svn.danwebb.net/external/rails/plugins/minus_mor

Now we can use in views new kind of files .ejs templates. They are just like .rhtml, but instead of embedding Ruby code in HTML, You use JavaScript as an native language, and insert Rails/Ruby code with well known <%= and <% tags. This tags work as in RHTML.

So what for it is useful? RJS templates are useful, but they are focused on AJAX (or at least this my perception of RJS) and sometimes is handy to create plain JavaScript code generated from Rails. For example to use controller actions to generate JS code as external scripts (for <script> tag). You can try emulate it with send_data function, but my practice shows there can be some obstacles (http://www.ruby-forum.com/topic/81043).

So Minus Mor is plugin which solves all this problems. You can write action in controller like:

 def show_route
    @pid = params[:id]
 end

and create corresponding app/views/controller_name/show_route.ejs:

function setPointsFromDB () {
load(false)
<%   Point.find(:all, :conditions => [ "route_id = ?", @pid]).each {|x|
      %>pt = new GLatLng(<%=x.lat.to_s%>,<%=x.lng.to_s%>)
points.push(pt)
<% end %>
line = new GPolyline(points,'#FF0000',5,0.5)
map.addOverlay(line);
}

This is real code snippet from my RNS application. As You can see it EJS template looks very similar to RHTML one.

Worth mention is one new helper js, it works to well know h helper. h helper escapes HTML special chars, js helper escapes output to be safe. Let take this EJS code

<%= link_to_remote "Delete this post", :update => "posts",
    :url => { :action => "destroy", :id => @pid } %>

It simple renders A tag for AJAX call. And assume we want to use it as argument to some JS function, so we need to do proper quotation. Let helper do the work:

<%= link_to_remote "Delete this post", :update => "posts", :url => { :action => "destroy", :id => @pid } %>

Result code is:

"<a href=\"#\" onclick=\"new Ajax.Updater('posts', '/route/destroy/49', 
{asynchronous:true, evalScripts:true}); 
return false;\">Delete this post</a>"

All is escaped as it should be. So that’s it! I found Minus Mor a very useful plugin, if You need to generate some JS code with data from Rails internals, it is right solution.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.