Closed ganlanyuan closed 6 years ago
You can supply your own Environment
where you add the filters using the env
option. That is kinda verbose though, so would be happy to merge a good pull request that adds a filters
option which accepts an object of filters, with name as key and filter function as value.
how exactly do we do that?
This is what I tried:
const gulp = require('gulp');
const gulp_nunjucks = require('gulp-nunjucks');
const nunjucks = require('nunjucks');
const customEnv = new nunjucks.Environment();
customEnv.addFilter('shorten', function(str, count) {
return str.slice(0, count || 5);
});
gulp.task('default', () =>
gulp.src([
'development/templates/*.njk',
'development/templates/**/pages/**/*.njk'
])
.pipe(gulp_nunjucks.compile(data, {
env: customEnv
}))
.pipe(gulp.dest('dist'))
);
Passing in the environment seemed to work fine, but unfortunately gulp-nunjucks does not find my templates?
Template render error in plugin 'gulp-nunjucks'
Message:
(unknown path)
Template render error: (unknown path)
Error: template not found: _partials/_html_head.njk
Is this a bug on the end of gulp-nunjucks, or am I doing something wrong here?
since you're passing a brand new constructor, you need to reinitialize the base path:
const customEnv = new nunjucks.Environment(new nunjucks.FileSystemLoader(src.html));
However this isn't working on recompiles when watching. Seems that the customEnv
needs to be defined on every compile. Passing a function doesn't work:
env.renderString is not a function
Think I'll switch to https://github.com/mohitsinghs/gulp-nunjucks-md for now.
Facing same issue with @EnzoEghermanne while trying to set the env:
Template render error: (unknown path)
web_1 | Template render error: (unknown path)
web_1 | Error: template not found: parts/layout.njk
See the nunjucks docs here, https://mozilla.github.io/nunjucks/api.html#custom-filters