A simple JavaScript template engine

Source: Internet
Author: User

Relatively simple, direct code bar:

(function (global) {var _version = ' 1.0.0 ', _setting = {opentag: ' <# ',/* start tag of logic code */ Closetag: ' #> ',/* end tag for logic code */maskopentag: ' <!-',/* start tag for comment */Maskcloseta G: End tag of '-!> '/* comment */}, _templatecache = {}, _escapehtml = function (str) {if (Typ EOF str = = = ' string ') {var reg =/& (?! #?\w+;) |<|>| "|" |                \//g, rules = {' & ': ' & ', ' < ': ' < ', ' > ': ' > ', ' ' ': ' ', ' ' ' ', ' ', '/': '/';            Return Str.replace (Reg, function (m) {return rules[m];});        } return str; }, _compile = function (source, key) {if (typeof key! = ' undefined ' && typeof _templatecache[ke            Y] = = = ' function ') {return _templatecache[key]; } var code = (function () {/* Reject comment code */var arr = (Source | |     "). Split (_setting.maskopentag);           Arrayeach (arr, function (i, O) {var _arr = O.split (_setting.maskclosetag);                        This[i] = _arr.length = = 1?                (i = = 0 _arr[0]: _setting.maskopentag + _arr[0]): _arr[1];                });            Return Arr.join (");            })();                    return _templatecache[key] = (function () {var Codearr = Code.split (_setting.opentag), Funarr = [' var $T = arguments[0];\n ', ' var $data = this | |                        {};\n ', ' var $escapeHTML = $T. escapehtml;\n ', ' var $htmlArr = [];\n ',                ' var $write = function () {Array.prototype.push.apply ($HTMLARR, arguments);};\n '];                    Arrayeach (Codearr, function (i, O) {var arr = o.split (_setting.closetag);                    if (arr.length = = 1) {Funarr.push (HTML (arr[0])); } else {Funarr.push (logic (arr[0]), HTML (arr[1]));                }                });                Funarr.push (' Return $HTMLARR. Join (""); ');                try {var fun = new Function (Funarr.join ('));                } catch (e) {var fun = new Function (' Return ' Template Error! "); } return function () {try {return Function.prototype.call.apply                    (fun, [arguments[0], _t]);                    } catch (e) {return e.name + ': ' + e.message;            }                };            })();                    function Arrayeach (arr, fun) {if (Object.prototype.toString.call (arr) = = = ' [Object Array] ') {                            if (typeof fun = = = "function") {for (var i = 0, len = arr.length; i < Len; i++) {            Function.prototype.call.apply (fun, [arr, I, arr[i]]);            }}}}} function html (code) {code = CO De replace (/"/g, ' \ \" '). Replace (/\r/g, ' \\r '). Replace (/\n/g, '                \\n ');            Return ' $write ("' + code + '); \ n ';                } function logic (code) {code = code.replace (/^\s+/g, ');                if (code.indexof (' = = ') = = = 0) {return ' $write (' + code.substring (2) + '); \ n ';                } else if (code.indexof (' = ') = = = 0) {return ' $write ($escapeHTML (' + code.substring (1) + ')); \ n ';                } else {return code + ' \ n '; }}}, _t = {version: _version, setting: _setting, Templatecach    E: _templatecache, escapehtml: _escapehtml, compile: _compile}; Global. T = Global. T | |    {}; for (var it in _t) {Global. t[It] = _t[it]; }}) (this);

The principle is simple, is to read the template string, the string split method to decompose the string and then parse processing, the final generation of a JavaScript method code, and then create a function through the new function

Even if the compiled template, the compiled template is actually a function, this function to receive data parameters, the following is an example:

<script id= "t_tmp" type= "text/template" >    <# if (Object.prototype.toString.call (this) = = = ' [Object Array]  ') {#>        <table>        <# for (var i = 0; i < this.length; i++) {#>            <tr>                <td><#= this[i][' name '] #></td>                <td><#= this[i][' age '] #></td>            </tr>        <#} # >        </table>    <#} #></script>

var data = [    {name: ' Xiaoming ', age:23},    {name: ' Xiaohong ', age:20}];var html = t.compile ($ (' #t_tmp '). html (), ' t_tmp ') (data);

The usage is also relatively simple.

A simple JavaScript template engine

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.