Node.js with Handlebars.js on server and client

dzm picture dzm · Apr 6, 2012 · Viewed 39k times · Source

I have an app in Node.js using Expressjs and Handlebars as the template engine.

Expressjs uses layouts and then renders views. The layout (layout.hbs) looks like this:

<!doctype html>
<html lang="en">
    <head>
    </head>
  <body>
    {{{body}}}
  </body>
</html>

The {{{body}}} is replaced server-side, within node.js when you access a route. For example:

app.get('/', function(req, res){
   res.render('index'})
})

Will replace the {{{body}}} tag with the contents of index.hbs.

Now, on the client side I'm using Backbone.js and want to use Handlebars for the views controlled via Backbone. The problem is that because these pages are already rendered through Handlebars, when I attempt to use Handlebars within it (or Handlebars within Handlebars) it doesn't work. There are no errors, it simply just doesn't replace tags with data.

Has anyone encountered this before or have any idea a work around?

Thank you!

Answer

Zachary Yates picture Zachary Yates · Dec 14, 2012

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.

  1. Install handlebars globally npm install handlebars -g
  2. Precompile your templates handlebars client-template1.handlebars -f templates.js
  3. Include templates.js <script src="templates.js"></script>
  4. Execute the template var html = Handlebars.templates["client-template1"](context);

https://stackoverflow.com/a/13884587/8360