Search code examples
javascriptnode.jsexpresshandlebars.jsexpress-handlebars

Pass absolute url path to handlebars view in express


I am trying to just set the canonical meta tag using an express server with handlebars as the templating engine. I cannot figure out how to get the absolute url path and pass it to the handlebars view. I was going to create a helper function in handlebars to do so but it would be outside of the req so I don't really know how to get the url or how to go about this. I would like to set the canonical dynamically and not manually. Thanks.

Here is my simple server:

const express = require('express');
const router = require('./routes/router');
const handlebars = require('express-handlebars');
const PORT = process.env.PORT || 5000;
const path = require('path');
const app = express();

var hbs = handlebars.create({
  defaultLayout: 'main',
  helpers: {
    canonical: function() {
      //get absolute url path
    }
  }
});

app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

router(app);

app.listen(PORT, err => {
  if (err) throw err;
  console.log(`ready at http://localhost:${PORT}`);
});

Solution

  • You shouldn't need a helper for this. You can add the value to res.locals and access it via Handlebars.

    app.use("*", function(req, res, next){
        res.locals.absoluteUrl = absoluteUrl; // Note, you'll need to calculate this yourself
        next();
    });
    

    In Handlebars, you access it as a standard variable:

    {{absoluteUrl}}