【分享/转】用js写一个模板引擎

来源:互联网 发布:淘宝风云团队怎么联系 编辑:程序博客网 时间:2024/06/08 18:16

优质文章分享:http://lvtraveler.github.io/

模板引擎在前后端都能用到,但是通过作为前端,我们只需要一些简单的模板引擎。

先上代码:

<!DOCTYPE html><html><head>    <title>模板引擎</title></head><body>    <div id="tpl" type="text/plain">        <p>Today: { date }</p>        <a href="/{ user.id|safe }">{ user.company }</a>    </div>    <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>    <script type="text/javascript">        var tpl = new Template($('#tpl').html());        var date= new Date();        var model = tpl.render({            date: date,            user: {                id: '0000',                company: 'babybus'            }        });        $('#tpl').html(model);        function Template(tpl) {            var                fn,                match,                code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&amp;\').replace(/"/g, \'&quot;\').replace(/\'/g, \'&#39;\').replace(/</g, \'&lt;\').replace(/>/g, \'&gt;\'); };'],                re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,                addLine = function (text) {                    code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');                };            while (match = re.exec(tpl)) {                if (match.index > 0) {                    addLine(tpl.slice(0, match.index));                }                if (match[2]) {                    code.push('r.push(String(this.' + match[1] + '));');                }                else {                    code.push('r.push(_html(String(this.' + match[1] + ')));');                }                tpl = tpl.substring(match.index + match[0].length);            }            addLine(tpl);            code.push('return r.join(\'\');');            fn = new Function(code.join('\n'));            this.render = function (model) {                return fn.apply(model);            };        }    </script></body></html>

这个我们能用这个模板引擎创建一个我们前端需要的html片段了。

这里面我们使用正则表达式去匹配字符串中的变量,当然,你要对js正则表达式熟练应用。

原文地址:http://www.liaoxuefeng.com/article/001426512790239f83bfb47b1134b63b09a57548d06e5c5000

0 0
原创粉丝点击