Introduce a miniature template for JavaScript

Source: Internet
Author: User
Tags join split

This article mainly introduces a JavaScript miniature template, the need for friends can refer to the

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):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The "//simple JavaScript template engine//John RESIG-HT tp://ejohn.org/-MIT Licensed (function () {var cache = {};   This.tmpl = function Tmpl (str, data) {//Judge whether we already have such a model Board, 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 template generation functionality//(it will be recorded in the cache). The new Function ("obj", "var p=[],print=function () {p.push.apply (p,arguments);};" +  //with () {} introduces the data as a local variable with the "with" ( obj) {p.push (' +  //convert template to not pure JavaScript code str. replace (/[rtn]/g, ""). Split ("<%"). Join ("T"). Replace (/(^|%> ) [^t]*) '/g, ' $1r '). Replace (/t= (. *?) %>/g, "', $, '"). Split ("T"). Join ("');") . Split ("%>"). Join ("P.push"). Split ("R"). Join ("") + "'); return P.join ('); ");  /To provide users with some basic functions of the curry return data? fn (data): FN; }; })();

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

?

1 2 3 4 5 6 7 8 9 10 <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:

?

1 2 3 4 5 <script type= "text/html" id= "User_tmpl" > <% for (var i = 0; i < users.length; i++) {%> <li><a H ref= "<%=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:

?

1 2 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:

?

1 2 3 4 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 works well in modern browsers ( The next version of Firefox will dramatically improve the performance of replace (/match/g, "replace")-so long expressions like these 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.