Best strategy to use HAML template with Backbone.js

Vlad Gurovich picture Vlad Gurovich · Mar 10, 2011 · Viewed 16.8k times · Source

Im getting into Backbone.js to structure the javascript code for my project and I love HAML for templating on the backend(rails), so Id like to use it for Backbone Views templating. I know there is several HAML ports to Javascript, like https://github.com/creationix/haml-js and backbone supports JST and mustache with ease.

Whats the best way to use haml templating instead.

Are there any downsides to using HAML on the client side? Performance, extra script load time(taken care by asset packaging tools like jammit)

Answer

Craig picture Craig · Mar 25, 2011

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.