I tried to create a JS template last time and found that the parsing template for that method is too complicated. I changed my mind this time. In general, the JS template must implement the JS Code Able to run <textarea id="tpl" style="width: 400px; height: 200px; border: 1px solid #f60;"><Div> HUST _ small C template engine <br/> <% for (var I in a) {%> <br/> <li ><%= I %>: <% = A [I] %> </LI> <br/> <% }%> <br/> </div> <br/> <A> </a> <a> </a> <A> </a></textarea>
Of course, there are still many bugs. For example, the supported separator labels are limited. For example, {, {% does not seem to work yet. There are also bugs in IE, which will be fixed in the future!
The following is the core code of the template engine:
/*** @ Author HUST _ small C * Email: hustcoolboy@gmail.com */(function (w) {W. template = template | {}; function template (options) {return this instanceof arguments. callee? This. init (options): new arguments. callee (options);} template. prototype = {init: function (options) {This. TPL = options. TPL; // The model version this.target?options.tar GET | options. TPL; // parse the rendered template Dom this. tplcontent = options. TPL. text | options. TPL. value; this. left = options. left | "<%"; // left delimiter this. right = options. rigoal | "%>"; // right separator this. body = []; this. compiled = ""; // compile the generated function this. data = options. data;}, parse: function () {var self = this; this. Tplcontent. Split (New Regexp ('(? = '+ This. Left +') | ('+ this. Right +'). Filter (function (K, v) {return! (New Regexp (self. right )). test (v );}). each (function (K, v) {If (New Regexp ('^' + self. left )). test (V) {If (New Regexp ('^' + self. left + '\ s * = '). test (V) {self. body. push (v. replace (New Regexp ('^' + self. left + '\ s * = (. *) '),' \ ttemp. push ($1); \ n '). replace (/\ n/g, '');} else {self. body. push (v. replace (New Regexp ('^' + self. left + '\ s *(. *) '),' $1 \ n '). replace (// \ n/g, '') ;}// else {self. body. push ('\ ttemp. push (\ "'+ v. replace (/\ n | \ T/g, '') + '\"); \ n') ;}}) return this. body. join ("") ;}, compile: function () {If (! This. compiled) {This. compiled = new function ("JSON", 'var temp = []; \ nwith (JSON) {\ n' + this. parse () + '} \ n return temp. join (""); ');} return this. compiled;}, render: function({this.tar get. innerhtml = This. compile () (this. data) ;}}) (this); array. prototype. filter = function (FN) {var temp = []; for (VAR I = 0, L = This. length; I <L; I ++) {This [I] & FN. call (this, I, this [I]) & temp. push (this [I]);} return temp;} array. prototype. each = function (FN) {var temp = []; for (VAR I = 0, L = This. length; I <L; I ++) {fn. call (this, I, this [I]);} return this ;}