This section describes a JavaScript micro-template.

Source: Internet
Author: User

This section describes a JavaScript micro-template.

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

The following is the Template Function Code (you can get a more refined version from the book Secrets of the JavaScript Ninja to be published ):
 

// 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 to 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 function // (it will be recorded in the cache ). new Function ("obj", "var p = [], print = function () {p. push. apply (p, arguments) ;}; "+ // use with () {}to introduce data as a local variable" with (obj) {p. push ('"+ // convert the Template into a non-pure 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 ('');"); // provides users with some basic Keri functions: return data? Fn (data): fn ;};})();

Your template code looks similar (this is not a required format, but I prefer it ):

 

<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><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 ignores it-and the search engine and screen reading will also ignore it. This is a good disguise code that can embed your template into your page. I like fast but casual technology. I only need one or two small templates to get lightweight and fast applications.

You can use it in a script like this:
 

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

You can pre-compile the result and use it later. If you use only one ID as a parameter (or template Code) to call the template function, it will return a pre-compiled function, you can call it later:
 

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


This is currently the most difficult way to resolve and convert code-you may not love it. However, he only has one of my favorite technologies: When character static search and static replacement are used in strings, such as split ("match "). join ("replace"), the execution speed is better-it does not seem intuitive but can work effectively in modern browsers (the next version of FireFox will greatly improve replace (/match/g, "replace") Performance-so this long expression is not needed now)

Enjoy it with ease-I'm curious about sudden changes in code. Even if it is simple, there are still many things that can be done with it.

Related Article

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.