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

允我心安 提交于 2020-01-11 15:47:13

问题


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?


回答1:


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';



回答2:


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



回答3:


Using express-handlebars is just a little bit different:

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


来源:https://stackoverflow.com/questions/25095991/how-to-set-a-variable-for-the-main-handlebars-layout-without-passing-it-to-every

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!