Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 482
mles Avatar asked Aug 02 '14 14:08

mles


People also ask

What does variable triple brace meaning in Handlebars?

Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}} . If you don't want Handlebars to escape a value, use the "triple-stash", {{{ . Source: https://handlebarsjs.com/guide/#html-escaping.

What is helper in Handlebars?

Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.


2 Answers

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';
like image 152
r0- Avatar answered Sep 28 '22 06:09

r0-


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
like image 27
gnowoel Avatar answered Sep 28 '22 06:09

gnowoel