Rendering A Rails Partial As A jQuery Template


A question was asked on twitter:

Screen shot 2011 06 22 at 10 52 47 PM

Here’s one of the answers that I sent to rob, in the form of a gist:

I’m using this solution in my current rails app and it’s a very elegant way to use an existing partial as a jQuery template. The only issue you have to solve, then, is how to get the “${value}” syntax populated into the rendered template fields. That, too, is simple.

Given this partial:

I need to turn “<%= model.value %>” into “${value}” so that the jQuery template will populate the data. To do that, we provide an @template_model instance of our model, populated with the “${value}” values, from our controller.

Easy-peasy. Our partial renders with the output of “this is a partial. ${value}” and when the jQuery template does its magic, it produces “this is a partial. this is some data” as the final result. From here, you can use jQueryUI’s dialog to open the rendered template as a dialog.

Rendering jQuery Templates With Backbone Views