gulp通过markdown json用jade生成html文件

标签 gulp pug markdown static-site

我正在使用gulp-markdown-to-jsongulp-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/

相关文章:

r - 在 R markdown 中创建列表和子项目不再起作用?

node.js - 使用 Visual Studio 时可以在不同文件之间拆分 gulp 任务吗?

javascript - JS任务一直在运行

javascript - Gulp 和 Browserify,使用 Node.js require(); 进行依赖管理。把 jQuery 放在上面?

node.js - express Jade 升级到最新的 throw 错误

html - 无 Jade express 发电机

javascript - 为什么客户端在 node + express + socket.io + jade simple app 中断开连接并重新连接

markdown - 在 Next.js 中使用 PrismJS 并使用备注突出显示 Markdown 中的代码

markdown - 如何转义某些文本的 Markdown 解析器?

node.js - Gulp-autoprefixer 抛出 ReferenceError : Promise is not defined