-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.js
47 lines (39 loc) · 1.3 KB
/
template.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
/**
* A very very simple templating engine. Mimics basic funcionality of Handlebars templates.
* @param template Template content
* @param params Object where keys are strings to be searched, and values are replacements to make.
* This may contain nested objects.
* @params prefix Only used when recursing.
*/
exports.renderTemplate = function(template, params, prefix='') {
Object.keys(params).forEach(function(k) {
let v = params[k];
if('object' === typeof v)
template = exports.renderTemplate(template, v, k + '.');
else
template = template.replace(new RegExp('\\{\\{' + regexQuote(prefix + k) + '\\}\\}', 'g'), escapeHtml(v));
});
//if this was not recursive call, clean up any unused template strings
if(prefix === '')
template = template.replace(/\{\{(.*?)\}\}/g, '');//'MISSING: [$1]');
return template;
};
/**
* Escapes any characters which are special characters in a regular expression.
*/
function regexQuote(s) {
return s.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:\-])/g, '\\$1');
}
function escapeHtml(s) {
if('string' !== typeof s)
s = String(s);
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return s.replace(/[&<>"']/g, m => map[m]);
}