I wrote this fast-templating function:
var templatize = function(string) {
return function (string) {
return string.replace(/{{(.*?)}}/g, function(pattern, match) {
value = this[match];
if (value) {
return value;
} else {
return pattern;
}
});
}.call(this, string);
}
Which does this:
var foo = "bar", bar = "foo";
templatize("We are {{foo}} and {{bar}}, but not {{crazy}}"); // "We are bar and foo but not {{crazy}}"
I'm quite happy with this except that I have scoping problem. For sure, the templatize
method will be accessible through namedscope, but then, the current context of execution of templatize
is not accessible in my function automatically.
Something like calling $.proxy(templatize, this)("We are {{foo}} and {{bar}}, but not {{crazy}}")
should work, right?
But I'd like to achieve this without needing to call $.proxy() (and without any jQuery preferably) so that context is automatically transfered to the execution one.
I'm struggling with .call()
, .apply()
, and other closures, but I think I read somewhere over the internet that it was possible. Thanks
why don't you pass an object containing the view variables? would be cleaner then potentially displaying any existing variable in your view.
You can avoid using jQuery doing this :
In case you want to use
jQuery.proxy()
, wrap the replacement function :In both cases you can bind the data source to
this
usingcall
:Going further
You could optimize by compiling the template for reuse :
Usage example :
Regarding the example above, here is the function returned by
compile
:Note that you can use an array as well :
Performance test : http://jsperf.com/template-compiling.