Search code examples
node.jsgulptemplate-enginenunjucks

Globbing in template path not working in nunjucks with gulp


I'm using this gulp plugin to use nunjucks to make HTML management easier.

https://github.com/carlosl/gulp-nunjucks-render

gulp.task('default', function () {
  return gulp.src('src/templates/*.html')
    .pipe(nunjucksRender({
      path: ['src/templates/'] // String or Array
    }))
    .pipe(gulp.dest('dist'));
});

I want to keep my templates and partials of specific pages under page's directory in different folders so I tried this to keep the path as

path: ['src/templates/', 'src/common-partials/', 'src/pages/**/**/includes/']

but it's not working.

Template render error: (unknown path)
  Error: template not found: component1.nunjucks

My setup

enter image description here


Solution

  • The path option doesn't support globbing. You have to pass each path individually:

    gulp.task('default', function () {
      return gulp.src('src/templates/*.html')
        .pipe(nunjucksRender({
          path: ['src/templates/', 'src/pages/section_name/sub-page/includes'] 
        }))
        .pipe(gulp.dest('dist'));
    });
    

    If you really want to use globbing you can use the glob module to resolve each glob before passing it to gulp-nunjucks-render:

    var glob = require('glob');
    
    gulp.task('default', function() {
      var includeDirs = ['src/templates/', 'src/pages/**/includes'];
    
      return gulp.src('src/templates/*.html')
        .pipe(nunjucksRender({
          path: includeDirs.reduce(function(dirs, g) {
            return dirs.concat(glob.sync(g));
          }, [])
        }))
        .pipe(gulp.dest('dist'));
    });