2017-02-20 18:32:27 +00:00
|
|
|
import nunjucks from 'nunjucks';
|
|
|
|
import * as extensions from './extensions';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Render text based on stuff
|
|
|
|
* @param {String} text - Nunjucks template in text form
|
|
|
|
* @param {Object} [config] - Config options for rendering
|
|
|
|
* @param {Object} [config.context] - Context to render with
|
2017-02-27 21:00:13 +00:00
|
|
|
* @param {Object} [config.strict] - Fail on undefined values
|
2017-02-20 18:32:27 +00:00
|
|
|
*/
|
|
|
|
export async function render (text, config = {}) {
|
|
|
|
const context = config.context || {};
|
2017-02-27 21:00:13 +00:00
|
|
|
const strict = config.strict;
|
2017-02-20 18:32:27 +00:00
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
2017-02-27 21:00:13 +00:00
|
|
|
const env = getNunjucksEnvironment(strict);
|
|
|
|
env.renderString(text, context, (err, result) => {
|
2017-02-20 18:32:27 +00:00
|
|
|
if (err) {
|
2017-02-27 21:00:13 +00:00
|
|
|
const sanitizedMsg = err.message
|
|
|
|
.replace(/\(unknown path\)\s*/, '')
|
|
|
|
.replace(/^Error: */, '')
|
2017-03-01 21:15:56 +00:00
|
|
|
.replace('attempted to output null or undefined value', 'undefined variable');
|
2017-02-27 21:00:13 +00:00
|
|
|
|
2017-02-20 18:32:27 +00:00
|
|
|
reject(new Error(sanitizedMsg));
|
|
|
|
} else {
|
|
|
|
resolve(result);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-02-27 21:00:13 +00:00
|
|
|
function getNunjucksEnvironment (strict = false) {
|
|
|
|
return strict ? _getStrictEnv() : _getNormalEnv();
|
|
|
|
}
|
|
|
|
|
2017-02-20 18:32:27 +00:00
|
|
|
// ~~~~~~~~~~~~~ //
|
|
|
|
// Private Stuff //
|
|
|
|
// ~~~~~~~~~~~~~ //
|
|
|
|
|
|
|
|
let _nunjucksEnvironment = null;
|
2017-02-27 21:00:13 +00:00
|
|
|
function _getNormalEnv () {
|
2017-02-20 18:32:27 +00:00
|
|
|
if (!_nunjucksEnvironment) {
|
|
|
|
_nunjucksEnvironment = nunjucks.configure({
|
|
|
|
autoescape: false,
|
|
|
|
});
|
|
|
|
|
|
|
|
for (const Cls of extensions.all()) {
|
|
|
|
_nunjucksEnvironment.addExtension(Cls.name, new Cls());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return _nunjucksEnvironment;
|
|
|
|
}
|
2017-02-27 21:00:13 +00:00
|
|
|
|
|
|
|
let _nunjucksStrictEnvironment = null;
|
|
|
|
function _getStrictEnv () {
|
|
|
|
if (!_nunjucksStrictEnvironment) {
|
|
|
|
_nunjucksStrictEnvironment = nunjucks.configure({
|
|
|
|
autoescape: false,
|
|
|
|
throwOnUndefined: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
for (const Cls of extensions.all()) {
|
|
|
|
_nunjucksStrictEnvironment.addExtension(Cls.name, new Cls());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return _nunjucksStrictEnvironment;
|
|
|
|
}
|