1

我想使用该node-pandoc模块从 Markdown 生成 PDF。但我需要即时创建那些降价。是否有任何 node.js 模板引擎可以生成纯文本/降价?

4

2 回答 2

0

Take a look at grunt-readme, which - although focused on generating README documentation from templates - is a good example of how you can generate markdown docs from templates.

于 2013-11-17T03:07:16.483 回答
0

我最近使用underscore和用rho编写的template纯文本文件(它也是一个纯文本到 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也能很好地完成这项工作。

于 2013-11-10T06:34:59.853 回答