mirror of
https://github.com/tomru/pdfer.git
synced 2026-03-03 22:47:25 +01:00
make pdfs
This commit is contained in:
33
templates.js
33
templates.js
@@ -1,30 +1,13 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function replaceOption(string, key, value) {
|
||||
const re = new RegExp(`\\$\{${key}\}`, 'g');
|
||||
return string.replace(re, value);
|
||||
}
|
||||
|
||||
function cleanUnsetVars(string) {
|
||||
const re = new RegExp('\\$\{[a-zA-Z-_]+\}', 'g');
|
||||
return string.replace(re, '');
|
||||
}
|
||||
|
||||
module.exports.get = (templateName, options, callback) => {
|
||||
const filename = path.join(__dirname, 'templates', templateName + '.template');
|
||||
const modulePath = path.join(__dirname, 'templates', templateName);
|
||||
let template;
|
||||
|
||||
fs.readFile(filename, 'utf-8', (err, template) => {
|
||||
if (err) {
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
const replaced = Object.keys(options).reduce((memo, key) => {
|
||||
return replaceOption(memo, key, options[key]);
|
||||
}, template);
|
||||
|
||||
const result = cleanUnsetVars(replaced);
|
||||
|
||||
callback(null, result);
|
||||
});
|
||||
try {
|
||||
template = require(modulePath);
|
||||
callback(null, template(options));
|
||||
} catch (e) {
|
||||
callback(`${templateName} not found!`);
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user