Node.js with Handlebars.js on server and client
You should use pre-compiled client templates. They are faster executing and allow you to use the same template language on the server and client.
- Install handlebars globally
npm install handlebars -g
- Precompile your templates
handlebars client-template1.handlebars -f templates.js
- Include templates.js
<script src="templates.js"></script>
- Execute the template
var html = Handlebars.templates["client-template1"](context);
An easy way to do this is to just append a \
before the {{
in a Handlebars file. For example:
<script type="text/x-template" id="todo-item-template"><div class="todo-view"> <input type="checkbox" class="todo-checkbox" \{{checked}}> <span class="todo-content" tabindex="0">\{{text}}</span></div><div class="todo-edit"> <input type="text" class="todo-input" value="\{{text}}"></div><a href="#" class="todo-remove" title="Remove this task"> <span class="todo-remove-icon"></span></a>
The above code will be rendered on the client with the {{..}} tags preserved.
Yup, it's a sticky problem --- kind of like the quoting problems in shell scripts which become a rats' nest of quoted quotes.
My solution is to use jade (a la haml) in expressjs (server-side) to output handlebars based templates for the client. This way, the server uses one syntax (jade), and the client uses another (handlebars). I am at the same crossroads as you, so I have the same challenge.
Of course, jade is not essential (though it's ready-made for expressjs). You could choose any (non-handlebars) template engine for the server, and/or you could use handlebars on the server with your non-handlebars templating on the client --- as long as the two syntaxes of your chosen templating engines do not collide. Since I'm using emberjs on the client and it uses handlebars syntax (by default), I prefer using emberjs + handlebars syntax on the client. So expressjs + jade became a natural fit for the server.