jonschlinkert
jonschlinkert

Reputation: 11007

Handlebars helper to retrieve the basename of the file in which it is used

I'm looking for a way to create a helper that simply renders the basename of the file in which the template was placed, and without requiring any additional parameters, like so: {{ basename }}.

In other words, if I used this helper inside two partials, say header.hbs and navbar.hbs, I would expect the name of each partial to be render in the output wherever they were used.

I've looked for hours and can't find any answers to this. Any direction or guidance would be appreciated.

Upvotes: 2

Views: 2834

Answers (2)

jonschlinkert
jonschlinkert

Reputation: 11007

This is something that needs to be exposed on the context when rendering a file.

For example, assuming we have a template at the file path "some/template.hbs", which has something like the following in

Basename is: "{{basename}}"

We can render it like this:

var fs = require('fs');
var hbs = require('handlebars');

var filepath = 'some/template.hbs';
var tmpl = fs.readFileSync(filepath, 'utf8');

var fn = hbs.compile(tmpl);
var str = fn({
  path: filepath,
  basename: path.basename(filepath)
});
console.log(str);
// Basename is: "template.hbs"

Upvotes: 1

Hatchware
Hatchware

Reputation: 242

Without knowing much about your setup here is an approach.

You need to register a helper inside your render function. You will then call render instead of compile. Note the below is for the backend, but you can easily adapt it to your environment.

Handlebars has no notion of your environment so you need to set it globally somewhere.

exports.render = function (name, req, context) {
    if (isBrowser()) {
        throw new Error('Render cannot be called client-side.');
    }
    handlebars.registerHelper('basename', function() {
        var host = globalBasenameSetFromEnvironment;
        return  host;
    });
    if (!handlebars.templates[name]) {
        throw new Error('Template Not Found: ' + name);
    }
    return handlebars.templates[name](context);
};

Upvotes: 1

Related Questions