Home  >  Article  >  Web Front-end  >  Tips for getting started with template.js

Tips for getting started with template.js

一个新手
一个新手Original
2017-10-16 09:11:524611browse

template.js插件在表格渲染方面还是极其出色的,当数据在异步加载后不用使用传统的方式,在ajax里面拼接html语句加载表格,直接用这个插件将ajax传回来的json数组直接渲染在前端中,省下了不少时间。

我使用template.js主要是满足项目实现为目的,不是深入探究,总结一下我在项目里基本使用这个插件哪些功能,主要是数据的展示,each循环以及if语句简单使用。

基本上会了这些,使用ajax异步加载出来一个表格是没什么问题的。

1、引入template.js插件

引用jquery.template.js

2、基本使用方法:在.jsp中需要用到此模板渲染表格的地方,标记id:

<table class="table-form" id="demoTable"></table>

一般在jsp的底部使用:

<script type="text/html" id="demoTableTemp">
    <tr>
        <td>\${index}</td>
        <td>\${name}</td>
        <td>\${sex}</td>
        <td>\${age}</td>
    </tr>
</script>

 在js中使用异步加载一般得到的数据格式需要是一个数组,组装格式如下:

[{
"index":1,
"name":"张三",
"sex":"男",
"age":"18"
},{
"index":2,
"name":"李四",
"sex":"女",
"age":"18"
}]

js中将此data引入jsp中时应用:(不仅可以使用id,也可以使用.class)

$(&#39;#demoTableTemp&#39;).tmpl(data).appendTo(&#39;#demoTable&#39;);

 此时会按照数组的格式,循环渲染表格模板。

 3、each循环:表格行中单元格是数组的情况,需要用到循环嵌套的方法:(暂时没有很好的方法)

如果组装的data中,此项是数组时,需要将它再次组装,组装成对象内嵌套对象的模式,比如:

 

此时应将它组装为:

[
    {
       ...
        "likes": {
            "like": "apple",
            "like": "football"
        }
    },
    {
        ...
        "likes": {
            "like": "orange",
            "like": "book"
        }
    }
]

View Code

此时在jsp的底部应当使用each循环:

<script type="text/html" id="demoTableTemp">
    <tr>
        <td>\${index}</td>
        <td>\${name}</td>
        <td>\${sex}</td>
        <td>\${age}</td><td>
    {{each likes}}
    <p>\${like}</p>
    {{/each}}
</td>
    </tr>
</script>

4:使用if判断语句:

比较简单的属于单双行不一致问题:

使用{{if (index+1)%2 == 0 }}{{/if}}和{{if (index+1)%2 == 1 }}{{/if}}可以满足基本的判断语句

The above is the detailed content of Tips for getting started with template.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Operation of tabs in jsNext article:Operation of tabs in js