How does JavaScript Micro-Templating work? -
when go through how javascript micro-templating source code, confused 2 questions:
- why use new function rather define common function?
- why in new function there no direct reference data parameter, can replace correct value. expect use data[$1] correct value data.
the code:
(function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // figure out if we're getting template, or if need // load template - , sure cache result. var fn = !/\w/.test(str) ? cache[str] = cache[str] || tmpl(document.getelementbyid(str).innerhtml) : // generate reusable function serve template // generator (and cached). new function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // introduce data local variables using with(){} "with(obj){p.push('" + // convert template pure javascript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // provide basic currying user return data ? fn( data ) : fn; }; })();
- expect statement such
"<div>",name,"</div>"
can use statement. string.replace() returns string. expect symbol rather string. in situation, evel type best option. got. please correct me, if wrong. - the key second question:
- currying function
- with statement
example:
function wrapperfn(data) { var fn = function anonymous(obj) { var p=[], print=function(){p.push.apply(p,arguments);}; with(obj) { p.push(' <p>',name,'</p> '); } console.log("p.join(''):", p.join('')); return p.join(''); } return fn(data); }
why use new function rather define common function?
because needs eval
code in template. fancy replaces, translates templating language valid js statements. (still being strings) made function body via new function
. example, user_tmpl
example become
function(obj) { var p=[], print=function(){p.push.apply(p,arguments);}; with(obj) { p.push(' '); ( var = 0; < users.length; i++ ) { p.push(' <li><a href="',users[i].url,'">',users[i].name,'</a></li> '); } p.push(''); } return p.join(''); }
why in new function there no direct reference data parameter, can replace correct value. expect use data[$1] correct value data.
because data
argument (if present) passed obj
parameter new fn
function, right in return clause (last line of code). can access properties (users
) variables due with
statement. if data not passed, newly created function returned instead of
var res = tmpl("templname", data);
you can use
var tmplfn = tmpl("templname"); var res = templfn(data);
this concept called partial application, here wrongly referred "currying" (a similar, quite different concept).
Comments
Post a Comment