Search code examples
node.jsexpressglobalswig-template

Setting global variables for swig with nodejs or express render


I am putting a bootstrap framework together for myself in node using express and swig as the tpl engine.

I am used to working with frameworks such as ezpublish where ini settings can be pulled from the tpl code. I don't actually like this way.

However there will always be content that the required in multiple places eg:

//general site details
module.exports = {
    'siteName' : 'my site',
    'emails' : {
        'noReply' : '[email protected]',
        'accouts' : '[email protected]',
        'support' : '[email protected]'
    },
    'website': 'www.mysite.com',
    'googleAnalytics': {
        'trackingID': 'UA-123321213-1'
    }
};

I would like to be able to always have the above information available to any swig template the app uses. Is there a way to define these as globals so i don't have to pass them through on every single route?

Doing this in each route seems crazy:

app.get('/profile', isLoggedIn, function(req, res) {
        res.render('private/profile.html', {
            user : req.user,
            siteDetails: siteDetails /* this should be automatic */
        });
    });

If it is not possible to set gloabls with the swig tpl engine, is it possible to set an object to always be passed through to the express render functionality?

Thanks John


Solution

  • I found the answer:

    app.locals.siteDetails = require('./config/site');
    

    Then once in the template, you can access the object via:

    {{siteDetails.googleAnalytics.trackingID}}