UNPKG

@ngouy/easy-template

Version:

Easy template language in js, with only variable substitution. Inspired from same ruby gem

23 lines (19 loc) 704 B
"use strict"; /** * @param {string} text - the string containing your template. * @param {object} variables - containing the values to substitute in place of the keys enclosed by { and }. */ function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function process(text, variables) { var regexp = new RegExp("(\\\\\\{)|((?=\\\\)(?:\\\\\\\\))*" + Object.keys(variables).map(function (k) { return escapeRegExp("{" + k + "}"); }).join('|'), 'gi'); return text.replace(regexp, function (s) { return s[0] === "\\" ? s[1] : (variables[(s.slice(1, -1) || '').toLocaleLowerCase()] || '').toString(); }); } module.exports = { process: process };