Created
July 27, 2017 11:32
-
-
Save davidgarsan/c99952665b937fa9e5d71651a8649627 to your computer and use it in GitHub Desktop.
Template Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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