sindresorhus / gulp-nunjucks

Precompile Nunjucks templates
MIT License
152 stars 20 forks source link

Is there a way to add custom-filters? #19

Closed ganlanyuan closed 6 years ago

ganlanyuan commented 7 years ago

See the nunjucks docs here, https://mozilla.github.io/nunjucks/api.html#custom-filters

sindresorhus commented 7 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.

hanakin commented 7 years ago

how exactly do we do that?

e2o commented 7 years ago

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?

ivancuric commented 7 years ago

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.

ganlanyuan commented 7 years ago

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