How to stock my Mustache / Handlebars templates in separate files?

mdcarter picture mdcarter · Oct 17, 2011 · Viewed 15k times · Source

I'm using handlebars.js on a project and I'm starting to have a fair amount of templates. For now they are stored in my main template app file, like this :

<script id="avatar_tpl" type="text/html">
bla bla bla {{var}} bla bla bla
</script>

I'm wondering if there is a way to put them in a separate file like a .js file or something, to avoid stacking them up in my source code page.

I'm aware that there are several solutions to call theses templates via Ajax, but that seems to result in too much unnecessary requests for me.

Thank you

Answer

Mauvis Ledford picture Mauvis Ledford · Oct 21, 2011

I created and open-sourced NodeInterval for this exact same problem of too many js templates in my HTML page.

It allows you to put all your templates into a templates folder organized in whatever hierarchy you like. It has a built in watch capability so that as you modify any of these templates it automatically updates your HTML page. I use it alongside SASS for my CSS.

I use it daily with underscore templates but it should work fine with moustache templates as well:

https://github.com/krunkosaurus/NodeInterval