Best strategy to use HAML template with Backbone.js
I know you already mentioned it but I would suggest using haml-js with Jammit. Simply include haml.js in your javascripts and in your assets.yml add template_function: Haml
as well as including your template files in to a package. e.g.
javascript_templates: - app/views/**/*.jst.haml
Then in your views you can include this package (= include_javascripts :javascript_templates
) and Jammit will package any .jst.haml files in to window.JST['file/path']
. (If you view page source you should see a javascript file like <script src="/assets/javascript_templates.jst" type="text/javascript"></script>
)
To use these templates simply call one of those JSTs Jammit created. i.e.
$('div').html(JST['file/path']({ foo: 'Hello', bar: 'World' }));
And Jammit will use the Haml-js template function function to render the template.
Note: Be sure to point to the github repo of Jammit in your Gemfile to get the latest version that supports newline characters necessary for haml-js to work.
I'm about to give haml-coffee a shot. (no pun intended) I can't sing the praises of coffeescript enough; plus it's a default now in Rails 3.1. Now I can embed coffeescript within my favorite templating language, and pre-compile the lot.
Oh, the joy.. now to get it to work.
I know this would somewhat going around the question but here we go :)
I my rails app I use haml for all views on the backend. It is awesome. For some reasons (mainly i18n), I do not like to use templates on the client side. This is how I do it:
- create all your template in ruby haml and store them into script tag with a funky type (i use text/js-template). This will create prerendered html that you can play with with jquery and backbone.
- when you create your backbone views, load the stored template and append it to your document
- Render your view by altering the preexisting template
You deal only with html and jQuery is awesome for that. For some views that do not requires i18n, I use underscore templating because it's already there.
As for haml templating performance, it seems mustache and handlebars are faster.