node.js - 从模板生成 Markdown

标签 node.js markdown pandoc

我想使用 node-pandoc 模块从 Markdown 生成 PDF。但我需要动态创建这些 Markdown。有没有可以生成纯文本/markdown 的node.js 模板引擎?

最佳答案

我最近使用过underscore模板,其中包含用 rho 编写的纯文本文件(这也是一个纯文本到 html 工具,如 Markdown)生成带有动态数据的纯文本文档:

这是我的模块的代码(如果不需要,请忽略缓存):

// compiler.js
'use strict';

var fs = require('fs')
  , path = require('path')
  , _ = require('underscore');

var cache = {};

exports.getTemplate = function(templateId, cb) {
  // Use your extension here
  var file = path.join(__dirname, templateId + ".rho");
  fs.stat(file, function(err, stat) {
    if (err) return cb(err);
    // Try to get it from cache
    var cached = cache[templateId];
    if (cached && cached.mtime >= stat.mtime)
      return cb(null, cached.template);
    // Read it from file
    fs.readFile(file, { encoding: 'utf-8' }, function(err, data) {
      if (err) return cb(err);
      // Compile it
      var template = _.template(data);
      // Cache it
      cache[templateId] = {
        mtime: stat.mtime,
        template: template
      };
      // Return it
      return cb(null, template);
    });
  });
};

exports.compile = function(templateId, data, cb) {
  exports.getTemplate(templateId, function(err, template) {
    if (err) return cb(err);
    try {
      return cb(null, template(data));
    } catch (e) {
      return cb(e);
    }
  });
}

现在的用法。假设您有包含以下内容的 hello.rho:

# Hello, <%= name %>!

We are happy to have you here, <%= name %>!

你可以像这样编译它:

require('./compiler').compile('hello', { name: 'World' }, function(err, text) {
  if (err) // Handle the error somehow
    return console.log(err);
  console.log(text);
  // You'll get "# Hello, World!\n\nWe're happy to have you here, World!"
  // Now chain the compilation to rho, markdown, pandoc or whatever else.
});

如果你不喜欢下划线,那么我猜ejs也能很好地完成这项工作。

关于node.js - 从模板生成 Markdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18137649/

相关文章:

templates - 如何在 Go 中使用 Blackfriday 将 markdown 渲染为 html?

lua - Pandoc 编号示例列表不适用于自定义编写器

javascript - 如何在Ajax中调用Express路线?

regex - Node 表达中的正则表达式

windows - 在 Node JS 上生成 (Windows Server 2012)

node.js - 有时我会收到带有多部分表单的无效 csrf token

多级别 R Markdown 项目符号列表

css - 如何修改ipython notebook markdown单元格的线宽

pdf - 使用 Pandoc 时如何更改自动 TOC 的 header ("Contents")?

需要 pandoc 版本 1.12.3 或更高版本,但未找到(R Shiny )