zoukankan      html  css  js  c++  java
  • JSON JQUERY 模板

    用JSON从服务器端返回数据已是大家公认的标准,因为它短小精悍,使用方便.可是在客户端再现数据也是一个不小的问题,用javascript处理经常会遇到很繁琐的事.尤其大批量具有相同结构的数据,例如表格,处理方式不尽如意.如果能有一个模板控件,就像服务器端asp.net Gridview或者repeater一样的东西就好很多.最近看到一个非常优秀的解决方案,让我在使用方便的同时不得不为作者的精巧设计而作一番感叹.该解决方案用了区区二十几行代码,实现了别人要用几十甚至上百K的js库所做的工作.它就是John Resig 的 Microtemplating engine.大师Rick Strahl有一篇文章专门对此作了详细讲述(Client Templating with Jquery).我在这里把最核心部分提取出来以方便国人学习。

    下面一段程序就是microtemplating engine.

    var _tmplCache = {}
    this.parseTemplate = function(str, data) {
        /// <summary>
        /// Client side template parser that uses <#= #> and <# code #> expressions.
        /// and # # code blocks for template expansion.
        /// NOTE: chokes on single quotes in the document in some situations
        ///       use &rsquo; for literals in text and avoid any single quote
        ///       attribute delimiters.
        /// </summary>    
        /// <param name="str" type="string">The text of the template to expand</param>    
        /// <param name="data" type="var">
        /// Any data that is to be merged. Pass an object and
        /// that object's properties are visible as variables.
        /// </param>    
        /// <returns type="string" />  
        var err = "";
        try {
            var func = _tmplCache[str];
            if (!func) {
                var strFunc =
                "var p=[],print=function(){p.push.apply(p,arguments);};" +
                            "with(obj){p.push('" +
                
                str.replace(/[\r\t\n]/g, " ")
                   .replace(/'(?=[^#]*#>)/g, "\t")
                   .split("'").join("\\'")
                   .split("\t").join("'")
                   .replace(/<#=(.+?)#>/g, "',$1,'")
                   .split("<#").join("');")
                   .split("#>").join("p.push('")
                   + "');}return p.join('');";
    
                //alert(strFunc);
                func = new Function("obj", strFunc);
                _tmplCache[str] = func;
            }
            return func(data);
        } catch (e) { err = e.message; }
        return "< # ERROR: " + err.htmlEncode() + " # >";
    }
    

    如何使用:

    parseTemplate($("#ItemTemplate").html(),              { name: "rick", address: { street: "32 kaiea", city: "paia"} } );

    上面程序所用的模板:

    <script id="ItemTemplate" type="text/html"> <div>    <div><#= name #></div>    <div><#= address.street #></div> </div></script>

    如果想用循环:

     
    $.each(dataarray,function(index,dataItem){
    parseTemplate($("#ItemTemplate").html(),  dataItem );
    })
    

    很简单很精巧吧?

  • 相关阅读:
    基于 BP 神经网络的识别手写体数字
    【science封面文章】Human-level concept learning through probabilistic program induction
    漫谈小样本的类人概念学习与大数据的深度强化学习
    Setting up a Deep Learning Machine from Scratch (Software)
    Building Apache Thrift on CentOS 6.5¶
    ---Ubuntu 14.04下配置caffe---
    markdown基本语法说明
    Andrew ng清华报告听后感
    Median of Two Sorted Arrays
    LeetCode Question Difficulty Distribution
  • 原文地址:https://www.cnblogs.com/brucepark/p/jquerytemplate.html
Copyright © 2011-2022 走看看