Forked from WebReflection/String.prototype.template.js
Last active
August 29, 2015 14:22
-
-
Save jhliberty/7dca524d18c6c667a7c2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // new: accepts an optional transformer as first argument | |
| // str.template({key:value}); | |
| // or | |
| // str.template(htmlEscaper, {key:value}); | |
| String.prototype.template = function (fn, object) { | |
| // Andrea Giammarchi - WTFPL License | |
| var | |
| hasTransformer = typeof fn === 'function', | |
| prefix = hasTransformer ? '__tpl' + (+new Date) : '', | |
| stringify = JSON.stringify, | |
| re = /\$\{([\S\s]*?)\}/g, | |
| evaluate = [], | |
| i = 0, | |
| m | |
| ; | |
| while (m = re.exec(this)) { | |
| evaluate.push( | |
| stringify(this.slice(i, re.lastIndex - m[0].length)), | |
| prefix + '(' + m[1] + ')' | |
| ); | |
| i = re.lastIndex; | |
| } | |
| evaluate.push(stringify(this.slice(i))); | |
| // Function is needed to opt out from possible "use strict" directive | |
| return Function(prefix, 'with(this)return ' + evaluate.join('+')).call( | |
| hasTransformer ? object : fn, // the object to use inside the with | |
| hasTransformer && fn // the optional transformer function to use | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment