Skip to content

Instantly share code, notes, and snippets.

  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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 & me - WTFPL License
var
hasTransformer = typeof fn === 'function',
stringify = JSON.stringify,
re = /\$\{/g,
strings = [],
values = hasTransformer ? [] : strings,
i = 0,
l = this.length,
c,
n,
str,
m
;
while ((m = re.exec(this))) {
str = this.slice(i, m.index)
if (str.length) {
strings.push(hasTransformer && str || stringify(str));
}
n = 1;
i = m.index + 2;
while (i < l) {
c = this[i++];
n += ((c == '{') && 1) || ((c == '}') && -1) || 0;
if (!n) {
values.push('(' + this.slice(m.index + 2, i - 1) + ')')
break;
}
}
}
if (i < l) {
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
);
};
// --
function uc(strings /* ...values */) {
return ([].slice.call(arguments, 1)).reduce(function (a, v, i) {
a.push(strings[i]);
a.push(String(v).toUpperCase());
return a;
}, []).join('');
};
function f(_) { return 'foo'; }
console.log('${num} is the loneliest number'.template({num: 'One'}));
// One is the loneliest number
console.log('hm ... ${f({a: {b : 1}})}'.template({f: f, a: 1}));
// hm ... foo
console.log('hm ... ${f({a: {b : 1}})}'.template(uc, {f: f, a: 1}));
// hm ... FOO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment