我正在使用gulp-markdown-to-json
和gulp-jade
我的目标是从 markdown 文件中获取数据,如下所示:
---
template: index.jade
title: Europa
---
This is a test.
抓取template:index.jade
文件并将其与其他变量一起传递给jade编译器。
到目前为止我有这个:
gulp.task('docs', function() {
return gulp
.src('./src/docs/pages/*.md')
.pipe(md({
pedantic: true,
smartypants: true
}))
.pipe(jade({
jade: jade,
pretty: true
}))
.pipe(gulp.dest('./dist/docs'));
});
我缺少一个步骤,其中读取来自 markdown 的 json,并在 jade 编译器运行之前将 jade 模板文件名提供给 gulp.src。
最佳答案
gulp-jade
是不适合您的用例的 gulp 插件。
如果您有要填充数据的模板流,请使用
gulp-jade
:gulp.src('*.jade') .pipe(...) .pipe(jade({title:'Some title', text:'Some text'}))
如果您想要在模板中呈现数据流,请使用
gulp-wrap
:gulp.src('*.md') .pipe(...) .pipe(wrap({src:'path/to/my/template.jade'})
您的情况有点困难,因为您需要为每个 .md
文件使用不同的 .jade
模板。幸运的是,gulp-wrap 接受一个函数,该函数可以为流中的每个文件返回不同的模板:
var gulp = require('gulp');
var md = require('gulp-markdown-to-json');
var jade = require('jade');
var wrap = require('gulp-wrap');
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var fs = require('fs');
gulp.task('docs', function() {
return gulp.src('./src/docs/pages/*.md')
.pipe(plumber()) // this just ensures that errors are logged
.pipe(md({ pedantic: true, smartypants: true }))
.pipe(wrap(function(data) {
// read correct jade template from disk
var template = 'src/docs/templates/' + data.contents.template;
return fs.readFileSync(template).toString();
}, {}, { engine: 'jade' }))
.pipe(rename({extname:'.html'}))
.pipe(gulp.dest('./dist/docs'));
});
src/docs/pages/test.md
---
template: index.jade
title: Europa
---
This is a test.
src/docs/templates/index.jade
doctype html
html(lang="en")
head
title=contents.title
body
h1=contents.title
div !{contents.body}
dist/docs/test.html
<!DOCTYPE html><html lang="en"><head><title>Europa</title></head><body><h1>Europa</h1><div><p>This is a test. </p></div></body></html>
关于gulp通过markdown json用jade生成html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36500547/