Passing current file name in to the nunjuck template

895 views Asked by At

is there some possibility to pass current folder name in to the nunjuck template?

Something like:

This folder name is {{currentFolderName}}

Output:

This folder name is navigation

from path for exmpl: blahblah/components/navigation

Thanks :)

1

There are 1 answers

0
Aikon Mogwai On

The source can be ambiguous e.g. if you use include-tag. Nonetheless you can define the source as template name passed to render-function. So straightforward way is to override render-method of nunjucks-environment.

// app.js
var nunjucks  = require('nunjucks');
var env = nunjucks.configure('views');

var _render = env.render;
env.render = function(name, context = {}, cb) {
    context.__filename = context.__filename || name;
    return _render.call(env, name, context, cb);
}

var html = env.render('test.html');
console.log(html);

// views/test.html
Source: {{ __filename }}

P.S. Be careful, this code may have side effects.