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