Node.js with Handlebars.js on server and client

综合技术 2018-02-13

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:


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

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

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!

Problem courtesy of: dzm


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.

Solution courtesy of: occam


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
  4. Execute the template var html = Handlebars.templates["client-template1"](context);

Discussion courtesy of: Zachary Yates

An easy way to do this is to just append a
before the {{
in a Handlebars file. For example:


The above code will be rendered on the client with the {{..}} tags preserved.

Discussion courtesy of: Tilo Mitra

I have worked around this by passing client-side templates through server-side templates.

So on the server-side read all your client-side templates to an array and pass it to your render function on the server-side

In your route handler do something like:

readTemplates(function(err, clientTemplates) {
  res.render("page", {
    clientTemplates: clientTemplates;   

And then in layout.hbs:

{{#each clientTemplates}}



Here I'm using file names without extensions as the template id so that they can be referenced from Backbone views. Oh, and remember to implement caching for production mode.

Yeah, this sucks.

I think we should write a Handlebars/Express/Connect helper for this.

Discussion courtesy of: Epeli

You have 2 options. The second is THE best way to go:

1) Escape the mustaches



2) Precompile

This will compile the template on the server before it goes to the client. This will make the template ready to use and reduces the burden on the browser.

Discussion courtesy of: jordanb

I didn't like the precompilation solution (because I want to define templates in the same file where I will use them) nor the naive {{
escape solution (because it needs the full Handlebars compiler and more javascript code) so I came up with an hybrid solution that uses Handlebars' helpers:

1) Register a new helper called "template" on server configuration

var hbs = require('hbs');
hbs.registerHelper("template", function(key, options){
    var source = options.fn().replace("\{{", "{{");
    var ret =
    'n' + 
        key + ' = function(opt){n' +
            'return Handlebars.template(' + hbs.handlebars.precompile(source) + ')(opt);n' +
        '}n' + 
    return ret;

2) Use it anywhere in your client-side webpage (with {{
escape for client-side parameters)

{{#template "myTemplate"}}

Hello {{}}!


(the server will precompile it in something like this)

    myTemplate = function(opt){
        return Handlebars.template(/* HBS PRECOMPILATED FUNCTION */)(opt);

3) Simply call the function where you need it in client-side javascript

var generatedHtml = myTemplate("world");   // = 

Hello world!

$("#myDiv").html(generatedHtml); // or whatever

Discussion courtesy of: Oneiros

Shameless self-promotion!

I wanted to do this same client/server sharing thing, so I wrote a little npm package to assist:


I whipped it up in a couple hours based on the command-line compiler in wycats' handlebars repo. It's not the greatest code in the world, but it's been getting the job done for me very well.

EDIT: I am no longer maintaining this package. If you would like to take over, please contact me via Github. I mainly use Jade templates now, so it doesn't make sense for me to continue as the maintainer.

Discussion courtesy of: Joel Wietelmann

This recipe can be found in it's original form on Stack Over Flow

Node.js Recipes

责编内容by:Node.js Recipes (源链)。感谢您的支持!


Is “return;” necessary/helpful when us... For example, are these two effectively the same? someFunction(val, callback){ callback(val);...
Detect if user is accessing my network (WIFI) usin... My question is a NodeJS newbie question. I would like to somehow detect if a user is accessing my ne...
Can’t insert to MongoDB with Node.js and Mon... i've got Node.js server and with Exressjs/Mongoose im trying to insert some embedded documents...
使用nodeJS的 crypto模块来为你的密码hash加盐... 这篇文章将向你解释如何使用 Node.js 的 Crypto 模块对你的密码进行加盐 hash 。在这里,我们将不会对不懂的密码存储方式进行详细的比较。我们将要做的是知道在 ...
Checklist: Node.JS production best practices Last updated: 07/07/2017 This is the biggest compilation of tips on running Node.JS in productio...