Introduction to a mini-template in JavaScript-js tutorial

Source: Internet
Author: User
This article mainly introduces a JavaScript micro-template. If you need it, you can refer to it. I have been using a small tool and find that it is very 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 ):


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.