SoFunction
Updated on 2025-04-06

Introduction to a miniature template for JavaScript

I've been using a gadget and found it very useful in building Javascript applications. It is a very simple template function, fast, supports caching, and is easy to use. I would like to share some tips in using it.

Here is the code for the template function (you can get a more refined version from the book Secrets of the JavaScript Ninja that is about to be published):
 

// Simple JavaScript Template Engine// John Resig - / - MIT Licensed
(function(){
 var cache = {};
 
  = function tmpl(str, data){
  // Determine whether we already have such a template, or we need to load the template  // And ensure that the result is saved to cache.  var fn = !/\W/.test(str) ?
   cache[str] = cache[str] ||
    tmpl((str).innerHTML) :
   
   // Generate a reusable function to provide template generation function   // (It will be logged into the cache).   new Function("obj",
    "var p=[],print=function(){(p,arguments);};" +
    
    //Introduce data as local variables by with(){}    "with(obj){('" +
    
    // Convert templates to unpure javascript code    str
     .replace(/[\r\t\n]/g, " ")
     .split("<%").join("\t")
     .replace(/((^|%>)[^\t]*)'/g, "$1\r")
     .replace(/\t=(.*?)%>/g, "',$1,'")
     .split("\t").join("');")
     .split("%>").join("('")
     .split("\r").join("\\'")
   + "');}return ('');");
  
  // Provide users with some basic curry functions  return data ? fn( data ) : fn;
 };
})();

Your template code will look similar to (this is not the prescribed format, but I prefer it):

 

<script type="text/html" >
 <div  class="<%=(i % 2 == 1 ? " even" : "")%>">
  <div class="grid_1 alpha right">
   <img class="righted" src="<%=profile_image_url%>"/>
  </div>
  <div class="grid_6 omega contents">
   <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
  </div>
 </div>
</script>

You can also embed scripts:
 

<script type="text/html" >
 <% for ( var i = 0; i < ; i++ ) { %>
  <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
 <% } %>
</script>


Tip: Embed the script into your page and the content-type is unknown (for example, in this example, the browser does not know how to execute the text/html script), then the browser will ignore it - and search engines and screen readings will also ignore it. This is a very good disguise code to embed your template into your page. I like to use fast but casual technology, I can get lightweight and fast application with just one or two small templates.

You can use it in the script like this:
 

var results = ("results");
 = tmpl("item_tmpl", dataObject);

You can precompile the results and use them later. If you call the template function using only one ID as a parameter (or a template code), then it returns a precompiled function that you can call later:
 

var show_user = tmpl("item_tmpl"), html = "";
for ( var i = 0; i < ; i++ ) {
 html += show_user( users[i] );
}


This is the most unstoppable way at the moment, parsing and converting code - you may not have love for this. But he only has one technique I like: when using static characters search and static replacement in strings, such as split("match").join("replace"), the execution speed is better - it doesn't look intuitive but can work effectively in modern browsers (the next version of FireFox will greatly improve the performance of replace(/match/g,"replace") - so long expressions like this are not needed in the future)

Enjoy it easily – I'm curious about the mutations in the code. Even if it's simple, there are still many things to do with it.