我想使用 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/