Wednesday, March 21, 2012

fetching ember.js Handlebars templates with jsonp from Scala on Play!

As a setup I should mention that our ember.js javascript application is hosted on a third party page. Since we're using ember.js, the best templating solution is to use Handlebars. The trivial use case of handlebars is to embed the templates in the page itself via a script tag of type="text/x-handlebars". In our case, we're hosted so we can't really control the host page and even if we could, we shouldn't litter it with our templates. Moreover, there are many templates we would use in edge usecases, fetching them all on load will not be a good idea.
The solution we came up with is to fetch the templates on demand or pre-fetch if we see the need coming. Its best to keep the templates as stand alone files, its easier to revision and A/B test with variation of them. On top of that, we must handle the cross domain issue. In our case we decided to go with jsonp instead of CORS. On the javascript side: Note that in the response, the function gets the template html as a string and pass it onto the Ember.Handlebars.compile function to compile it to a handlebars template. Ember.js makes the template globally accessible from code or as an embedded view via the Ember.TEMPLATES map. When creating an ember.js view one should simple point to the template id as in:
On the server side we use Play Framework 2.0. Over there we have a rout in the routes file as in: It basically passes the name of the template from the path and name of the jquery's jsonp callback from the url args.
On the scala side things look pretty simple. Naturally you would like to check for security properties, string injections and A/B testing groups. [plug] QWallet is hiring!

Creative Commons License This work by Eishay Smith is licensed under a Creative Commons Attribution 3.0 Unported License.