Saturday, October 1, 2011

Strict Mode Compatible Micro-Templating Engine


Recently I developed and published jQuery templating plugin http://www.eslinstructor.net/vktemplate/, which is built on very popular Micro-Templating engine written by John Resig. It is a super compact, simple to use and power templating solution. I enjoy to use it.
But... one thing I want to avoid. The thing is the "with()" statement. There are two reasons.

1. The first, and most important reason is the fact, that using "with()" is not recommended, and is forbidden in ECMAScript 5 strict mode.

2. The second reason is performance. Performance can be decreased  if we intencively access objects other then the object specified with the "with()" statement.

Here is the  version of the  ECMAScript 5's strict mode compatible Micro-Templating engine which I created and breefly tested a couple of days ago.


1 function _tmpl(str, data){ 
2 var fn = new Function("o",
3 "var p=[],print=function(){p.push.apply(p,arguments);};" +
4 " p.push('" +
5 str.replace(/[\r\t\n]/g, " ")
6 .replace(/'(?=[^%]*%>)/g,"\t")
7 .split("'").join("\\'")
8 .split("\t").join("'")
9 .replace(/<%=(.+?)%>/g, "',$1,'")
10 .replace(/<%=(.+?)%>/g, "',this.$1,'")
11 .split("<%").join("');")
12 .split("%>").join("p.push('")
13 + "');    return p.join('');");
14 return fn( data );
15 };

Of course, if we remove with() statement, we must explicetly refer to the object which otherwise would be specified with "with()" statement. So, we have to change our template notation:

{name:"john"}
<%= o.name %>
<% if( o.name ) {...} %>

In this notation "o" is related to the function's argumen at line #2 of the example above.

Pro: no forbidden "with()" statement, better performance and better code readability as template-related variables are shown explicetely with object notation and not mixed other javascript variables.

Con: a couple of extra characters per each object's variables.

Next week I gonna to finish testing  and apply this with-free solution to my current plugin.

No comments:

Post a Comment