gulp 模板路径中的 Globbing 在 nunjucks 中不起作用

Globbing in template path not working in nunjucks with gulp

我正在使用这个 gulp 插件来使用 nunjucks 来简化 HTML 管理。

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'));
});

我想将我的模板和特定页面的部分内容保存在页面目录下的不同文件夹中,所以我尝试将路径保持为

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

但它不起作用。

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

我的设置

我认为这两个 /**/**/ 可能是问题所在。 ** 模式匹配路径字符串中的多个级别,因此我不太确定其中两个行的行为应该是什么。以下应与您的目录匹配:

'src/pages/**/includes/'

也就是说,如果 nunjucks 首先支持 globbing(我在文档中找不到任何提及)。

path 选项不支持通配。您必须单独通过每条路径:

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'));
});

如果你真的想使用 globbing,你可以使用 glob 模块在将每个 glob 传递给 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'));
});