Friday, March 27, 2009

Rails js.rjs Templates vs the Nonexistent js.erb Template.

I wanted to add a javascript file to a rails project, but I wanted the javascript page to contain some dynamic content from activerecord. Normally you would just include the dynamic content in the web page, but I wanted to enable the inclusion of my javascript into someone elses page. (Nothing underhand, this would be done voluntarily).

At first I tried to save the javascript as an .rjs file. However this is not the correct place for a plain javascript file. Rjs is a template language that describes the changes to the dom of a page using ajax. The rjs is converted to javascript which makes use of the prototype library.

It would make sense to save the javascript file as type js.erb within the view, but this is not recognised by rails. I can understand why this is not supported, because it's a fairly obscure usage.

The workaround is to simply to save your javascript file as an html.erb file, and set the appropriate content type in your controller.

Lets suppose our javascript file want to write out the information from a table stored using ActiveRecord. In this example, there is a MyInfo model class, with an attribute called description.

// controller
def blah
@myinfo = MyInfo.find(:first)
response.content_type = "text/javascript"
render :layout => false
end

The javascript file would be something like this:

// blah.html.erb (javascript file with erb template)
Document.write("<div><%= @myinfo.description %></div>");


The javascript file would then be loaded from a regular web page, for example:

// web page using the javascript file.
<script type="text/javascript" src="/mycontroller/blah">
</script>

No comments:

Post a Comment