21

I'm using handlebars with nodejs and express. This is my main.handlebars file:

<!doctype html>
<html>
    <head>
        ...
    </head>
    <body>
        <div class ="container">
            ...
            <footer>
                &copy; {{copyrightYear}} Meadowlark Travel
            </footer>
        </div>
    </body>
</html>

So far I'm passing the copyright year to every route:

var date = new Date();
var copyrightYear = date.getFullYear();

app.get(
    '/',
    function( req, res) {
        res.render(
            'home',
            {
                copyrightYear: copyrightYear
            }
        );
    }
);

Is it possible to set the copyrightYear variable globally, so I don't have to pass it on to every route/view?

mles
  • 4,534
  • 10
  • 54
  • 94

3 Answers3

19

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';
r0-
  • 2,388
  • 1
  • 24
  • 29
  • How would this be used in the theme? Is it just `{{ copyright }}`? Or `{{ locals.copyright }}`? (I'm assuming the former, but also trying to poke you to include the information, to make this as complete as possible :) – Nic May 04 '17 at 00:33
  • @QPaysTaxes I was asking myself the same question and edited the answer with the info afterwards. – Zaroth Jul 28 '17 at 12:24
  • What about request level data? Like req.user.id? – AffluentOwl Nov 23 '19 at 07:45
14

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:

&copy; {{copyrightYear}} Meadowlark Travel
gnowoel
  • 1,451
  • 2
  • 10
  • 5
6

Using express-handlebars is just a little bit different:

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