Introduction to a micro-template of JavaScript _ basics

Source: Internet
Author: User

I've been using a gadget and found it useful in building JavaScript applications. It is a very simple template function that is fast, supports caching, and is easy to use. I would like to share some of the techniques used in the process of using it.

Here's the code for the template function (you can get a more refined version of the secrets of the JavaScript ninja that you're about to publish):

Simple JavaScript template engine
//John resig-http://ejohn.org/-MIT licensed
(function () {
 var cache = {};
 
 This.tmpl = function Tmpl (str, data) {
  //Determine if we already have such a template, or we need to load the template
  ///and ensure that the results are saved in the cache.
  var fn =!/\w/.test (str)?
   CACHE[STR] = Cache[str] | |
    Tmpl (document.getElementById (str). InnerHTML):
   
   //Generate a reusable function to provide the template generation feature
   //(it will be logged into the cache).
   The new Function ("obj",
    "var p=[],print=function () {p.push.apply (p,arguments);};" +
    
    //through with () {} introduces the data as a local variable
    "with (obj) {P.push ('" +
    
    ///convert template to not pure JavaScript code
    str
     . Replace (/[\r\t\n]/g, "")
     . Split (" <% "). Join (" \ T ").
     Replace (/((^|%>) [^\t]*) '/g, $1\r ').
     replace (/\t= (. *?) %>/g, "', $, '")
     . Split ("T"). Join ("');")
     . Split ("%>"). Join ("P.push").
     split ("\ r"). Join ("\ \")
   + ""); return P.join ('); ");
  
  To provide users with some basic functions of Gerty return
  data fn (data): FN;
();

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


<script type= "text/html" id= "Item_tmpl" >
 <div id= "<%=id%>" class= "<%= (i% 2 = 1? "Even": "")%> ">
  <div class=" Grid_1 alpha right >
    "/>
  </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& Gt;<a href= "<%=users[i].url%>" ><%=users[i].name%></a></li>
 <%}%>
</script>


Hint: The script is embedded in your page and Content-type is unknown (for example, in this case, the browser doesn't know how to execute the text/html script), then the browser ignores it-and the search engine and screen reader ignore it. This is a very good camouflage code that can embed your template into your page. I like to use fast but also with the technology, I only need one or two small templates, can be light and rapid application.

You can use this 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 using only one ID as an argument (or a 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]);


That's the last thing you can do to parse and convert code--you're probably not in love with that. But he's only one of my favorites: Static search and static substitution in strings, such as split ("Match"). Join ("replace"), perform better-- It doesn't look intuitive, but it works in a modern browser (the next version of Firefox dramatically increases the performance of replace (/match/g, "replace")-so long expressions like this are not needed later.

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.