Introduces a miniature template for JavaScript

  • 2020-06-19 09:44:52
  • OfStack

I've been using a gadget for a while and have found it useful in building Javascript applications. It is a very simple template function that is fast, cacheable, and easy to use. I'd like to share a few tips on how to use it.

Here's the template function code (you can get a more refined version from the soon-to-be published book Secrets of the JavaScript Ninja1) :


//  simple JavaScript A template engine 
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
 var cache = {};
 
 this.tmpl = function tmpl(str, data){
  //  Judge whether we already have this 1 Or we need to load the template 
  //  And make sure you save the results to the cache. 
  var fn = !/\W/.test(str) ?
   cache[str] = cache[str] ||
    tmpl(document.getElementById(str).innerHTML) :
   
   //  generate 1 Three reusable functions that provide template generation functionality 
   // ( It will be recorded in the cache ).
   new Function("obj",
    "var p=[],print=function(){p.push.apply(p,arguments);};" +
    
    //  through with(){} Introduce data as local variables 
    "with(obj){p.push('" +
    
    //  Convert templates to impure 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("p.push('")
     .split("\r").join("\\'")
   + "');}return p.join('');");
  
  //  Provide to users 1 Some basic coriolis functions 
  return data ? fn( data ) : fn;
 };
})();

Your template code will look something like this (this is not a specified format, but I prefer it this way) :



<script type="text/html" id="item_tmpl">
 <div id="<%=id%>" 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" id="user_tmpl">
 <% for ( var i = 0; i < users.length; i++ ) { %>
  <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
 <% } %>
</script>


Tip: If the script is embedded in your page and content-ES27en is unknown (in this case, the browser doesn't know how to execute the text/html script), the browser will ignore it - and so will the search engines and screen readers. This is a good camouflage code to embed your template in your page. I like to use fast and casual techniques, I only need 1 to 2 small templates, can be lightweight and fast application.

You can use it in a script like this:


var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);

You can precompile the results and use them later. If you call a template function with only 1 ID as an argument (or 1 template code), it returns a precompiled function that you can call later:


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


This is the last thing you can do right now, parsing and converting code -- you probably don't love it. But he has only one technique I like: when using static character searches and static substitutions in strings, such as split("match").join ("replace"), the execution is much faster -- it doesn't look intuitive but it works effectively in modern browsers (the next version of FireFox will dramatically improve the performance of replace(/match/g,"replace") -- so long expressions like this won't be needed in the future).

Relax and enjoy it - I'm curious about the mutations in the code. Even though it's simple, there are still a lot of things you can do with it.


Related articles: