How to set a variable for the main handlebars layout without passing it to every route? How to set a variable for the main handlebars layout without passing it to every route? express express

How to set a variable for the main handlebars layout without passing it to every route?


ExpressJS provides some kind of "global variables". They are mentioned in the docs: app.locals. To include it in every response you could do something like this:

app.locals.copyright = '2014';


For this case, you can alternatively create a Handlebars helper. Like this:

var Handlebars = require('handlebars');Handlebars.registerHelper('copyrightYear', function() {  var year = new Date().getFullYear();  return new Handlebars.SafeString(year);});

In the templates, just use it as before:

© {{copyrightYear}} Meadowlark Travel


Using express-handlebars is just a little bit different:

var handlebars = require('express-handlebars').create({    defaultLayout:'main',    helpers: {        copyrightYear: function() {            return new Date().getFullYear();        },    }});