Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monomon/e57537aea07bfb38ebd9 to your computer and use it in GitHub Desktop.
Save monomon/e57537aea07bfb38ebd9 to your computer and use it in GitHub Desktop.
ES6 Template like strings in ES3 compatible syntax.
// accepts optional transformer
// now transformers are compatible with ES6
String.prototype.template = function (fn, object) {'use strict';
// Andrea Giammarchi - WTFPL License
var
hasTransformer = typeof fn === 'function',
stringify = JSON.stringify,
re = /\$\{([\S\s]*?)\}/g,
strings = [],
values = hasTransformer ? [] : strings,
i = 0,
str,
m
;
while ((m = re.exec(this))) {
str = this.slice(i, m.index);
if (hasTransformer) {
strings.push(str);
values.push('(' + m[1] + ')');
} else {
strings.push(stringify(str), '(' + m[1] + ')');
}
i = re.lastIndex;
}
str = this.slice(i);
strings.push(hasTransformer ? str : stringify(str));
if (hasTransformer) {
str = 'function' + (Math.random() * 1e5 | 0);
strings = [
str,
'with(this)return ' + str + '(' + stringify(strings) + (
values.length ? (',' + values.join(',')) : ''
) + ')'
];
} else {
strings = ['with(this)return ' + strings.join('+')];
}
return Function.apply(null, strings).call(
hasTransformer ? object : fn,
hasTransformer && fn
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment