1
votes

I am trying to create a meta tag handlebars helper that grabs the url pathname and uses that value for a switch statement which will then return the string to my meta tag in HTML head, but I am not sure the best way to currently grab the url path for my switch statement. I tried window.location.pathname, but get an error that window is not defined. I know that the path module requires you to pass something to it to parse out, but I'm not sure what the best value would be for that. Can anyone help me?

Here is my handlebars helper file:

var path = require('path');

    var metaHelpers = function(hbs) {

    hbs.registerHelper('metaTitle', function(){
        var urlPath = path.dirname();
        console.log(urlPath);
        switch(urlPath) {
            case "/": {
                return 'Index Test'
            }
            break;
            case "/login": {
                return 'Login Test'
            }
            break;
            default: {
                    return 'No Meta Tag'
                }
            }
    });

    };

    module.exports = metaHelpers;
1
Are you using Express as your web framework?76484
@76484 yes I amcphill
I've tried req.originalUrl but received Cannot read property 'originalUrl' of undefinedcphill

1 Answers

1
votes

Since your templates are executed on the server there is no window object to query. Instead you must get the URL path from the current Request object. Fortunately, in Express the Request object has a path property.

However in order to implement your solution as a Handlebars helper you would need to find a way to pass the Request object (or at least its .path) to the helper from the view. I think a better solution would be to execute your helper logic and construct the title before the response is rendered.

Express has the concept of middleware which are functions that can modify the Request and Response objects on a per request basis. We could write a middleware function to construct the title for each request and then add it to the locals property of the Response object. Properties of the res.locals object will be available to the view(s) rendered for the current response.

app.use(function (req, res, next) {
    switch (req.path) {
        case '/':
            res.locals.title = 'Index Test';
            break;
        case '/login':
            res.locals.title = 'Login Test';
            break;
        default:
            res.locals.title = 'No Meta Tag';
    }
    next();
});

In our layout, we can access the title property as we would any other property of our view model.

<title>{{title}}</title>

For reference, this answer provides a similar solution, except that it assigns the req object to the res.locals.