Jquery-template的使用

  • Post author:
  • Post category:其他


个人博客原文地址:

http://www.ltang.me/2015/11/12/jquery-template-study/

之前的项目中用到了

jquery-template

这东西,这里做一下记录,以免遗忘。


Jquery-template的github地址

个人理解,Jquery-template是一个jquery的插件,作用是定义一个html的模板,将一串类似的数据使用模板的样式,添加到html页面的指定位置。

最开始,我在页面中使用ajax获取了一些数据,然后解析这些数据,并手动生成html内容,添加到一个

<div>

范围内。然而这种做法实在是太笨太丑了,需要不停地append字符串,累赘而不美观,写起来也累。因为是要生成一个

table

,事实上

table

中每一行都是类似的,只是数据不同,所以可以使用

Jquery-template

来定义一个

<tr>

模板,然后将所有的数据,按照模板的格式、样式添加到指定的

<table>

使用方式

  1. 建立一个模板

    1
    2
    3
    
    <script type="text/html" id="template">
        <tr><td data-content="name" data-format="AddAHrefToDiv"></td><td data-content="doc" data-format="fromMarkDown"></td></tr>
    </script>
    

    这个模板就是一个列表行,每一行有两列,

    data-content

    表示数据来源,

    data-format

    表示显示格式。


  1. 定义数据

    1
    2
    3
    
    var service = {};
    service['name'] = $(this).attr('name');
    service['doc'] = $(this).children('meta').children('version').text();
    

    可以看到

    name



    doc

    两个key跟上面模板中的

    data-content

    相互对应。

  2. 加载到指定位置


    $("#target").loadTemplate($('#template'), service);

    这样就完成..一半了。如果你在模板中不指定

    data-format

    的话,这样就已经可以用了。如果指定了,那么还有一个步骤。

  3. 定义数据格式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    $.addTemplateFormatter({
      
      AddAHrefToDiv : function(value, template){
        if(value.substring(0,1) == '~'){
          return "<a href='method.jsp?serviceName=" + serviceName + "&methodName=" + value.substring(1) + "'>" + value.substring(1) + "</a>";
        }else if(value.substring(0, 1) == '@'){
          return "<a href='struct.jsp?serviceName=" + serviceName + "&structName=" + value.substring(1) + "'>" + value.substring(1) + "</a>";
        }else if(value.substring(0, 1) == '#'){
          return "<a href='enum.jsp?serviceName=" + serviceName + "&enumName=" + value.substring(1) + "'>" + value.substring(1) + "</a>";
        }else{
          return value;
        }
      },
    
      fromMarkDown : function(value, template){
         return marked(value);
      }
    });
    

    这里添加了两个方法,分别对数据做不同的处理,并返回处理后的数据。第一步的模板中通过指定

    data-format

    ,将第二布中的数据按指定方法处理后,再将处理后的数据添加到模板。

当然,后来的后来,又抛弃了

Jquery-template

,改成了直接使用

jstl

for循环生成页面,更加直观和简洁,这里只是做个记录。



版权声明:本文为devotedwife原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。