2016-03-01 57 views
2

我正在设置使用Markdown和Nunjucks,通过Gulp生成静态页面的工作流程。目前两个任务我靠,这是:使用markdown和nunjucks的吞噬工作流程

gulp.task('templates', function() { 
    return gulp.src('app/templates/pages/*.nunjucks') 
     .pipe(nunjucksRender({ 
     path: ['app/templates/', 'app/templates/pages/'] 
     })) 
     .pipe(gulp.dest('app')); 
}); 

gulp.task('pages', function() { 
    gulp.src('app/pages/**/*.md') 
     .pipe(frontMatter()) 
     .pipe(marked()) 
     .pipe(wrap(function (data) { 
      return fs.readFileSync('app/templates/pages/' + data.file.frontMatter.layout).toString() 
     }, null, {engine: 'nunjucks'})) 
     .pipe(gulp.dest('app')) 
}); 

结构如下:

/app 
| index.html 
| 
+---css 
|  app.scss 
|  custom.scss 
| 
+---js 
|  app.js 
| 
+---pages 
|  index.md 
| 
\---templates 
    | layout.nunjucks 
    | 
    +---macros 
    |  nav-macro.nunjucks 
    | 
    +---pages 
    |  index.nunjucks 
    | 
    \---partials 
      navigation.nunjucks 

如果我运行gulp templates这编译成index.html的延伸布局/使用的应用程序index.nunjucks。 nunjucks。不过,我想用gulp pages来从index.md中绘制frontmatter和Markdown来生成index.html的内容。

我遇到的问题是pathing:鉴于上述结构,如何通过/app/templates/pages/index.nunjucks使用/app/pages/index.md作为/app/index.html的内容?目前该任务失败,出现在Template render error: (unknown path)

从本质上讲,我试图延长这到底是怎么实现的:Gulp Front Matter +Markdown through Nunjucks

回答

5

我有你设定运行的简化版本,它使用您发布完全相同的Gulpfile.js。它看起来像这样:

project/Gulpfile.js 
project/index.html 
project/app/pages/index.md 
project/app/templates/layout.nunjucks 
project/app/templates/pages/index.nunjucks 

index.md

--- 
title: Example 
layout: index.nunjucks 
date: 2016-03-01 
--- 
This is the text 

layout.nunjucks

<h1>{{file.frontMatter.title}}</h1> 

<div class="date">{% block date %}{% endblock %}</div> 

<div>{% block text %}{% endblock %}</div> 

index.nunjucks

{% extends "app/templates/layout.nunjucks" %} 

{% block date %} 
{{file.frontMatter.date}} 
{% endblock %} 

{% block text %} 
{{contents}} 
{% endblock %} 

的index.html运行gulp pages后:

<h1>Example</h1> 

<div class="date"> 
Tue Mar 01 2016 01:00:00 GMT+0100 (CET) 
</div> 

<div> 
<p>This is the text</p> 

</div> 

,你很可能得到错误是如何指定{% extends %}index.nunjucks或某些其他地方的路径最棘手的部分。

运行gulp时,它将当前工作目录(CWD)更改为Gulpfile.js所在的文件夹(在我的示例中为:project/)。默认情况下,nunjuck使用FileSystemLoader来搜索CWD来加载其他模板。这意味着您的.ununjucks文件中的所有路径都必须与CWD相关,即项目的基础文件夹。

理论上应该可以提供你自己的FileSystemLoader这样你就可以指定相对于index.nunjucks模板路径,但gulp-wrap使用consolidate内部抽象掉许多模板引擎的区别,我一直懒得弄清楚如何以及是否允许您提供自定义加载程序。

+0

这确实是个问题,并且在考虑它相对于工作目录的路径是更可取的,因为路径杂耍不是必需的。感谢一个彻底的,解释清楚的答案。 – OleVik