2016-03-01 52 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