Skip to content

Instantly share code, notes, and snippets.

@davidgarsan
Created July 27, 2017 11:32
Show Gist options
  • Save davidgarsan/c99952665b937fa9e5d71651a8649627 to your computer and use it in GitHub Desktop.
Save davidgarsan/c99952665b937fa9e5d71651a8649627 to your computer and use it in GitHub Desktop.
Template Builder
/**
* @desc Returns a template function builder.
* @param template - template string.
* @param params - Substitution params.
* @return {function} - Template function.
*
* @example
* var template = buildTemplate("Hello, my name is ${params}");
* template('David'); // Hello, my name is David
*
* var template = buildTemplate('Greetings from ${params[0]}, ${params[1]}, ${params[2]} and ${params[3]}');
* template('Kike', 'Pol', 'Jorge', 'Victor'); // Greetings from Kike, Pol, Jorge, Victor
*/
export default function (template) {
return new Function(
'var str = "' + template.replace(/(?:\r\n|\r|\n)/g, '<br />') + '";' +
'for(var i = 0; i < arguments.length; i++) {' +
'str = str.replace(RegExp("\\\\${params\\\\}|\\\\${params\\\\[" + i + "\\\\]\\\\}", "gi"), arguments[i]);' +
'}' +
'return str;'
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment