JS模板引擎jTemplates基础使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/BruceLiu_code/article/details/102650249

1.jTemplate简介

jTemplates是一个基于Jquery的js模板引擎插件。该引擎全部代码由JS实现,可以配合AJAX,JSON一起协同工作,模板内容可以用JS代码,实现了活动更新,可以自动从服务器更新模板生成的内容。

使用jTemplates,服务端只需要把对象集合序列化成json格式并传入客户端,客户端再把json对象填充模版生成列表,这样一服务端传输的只是json格式的字符串,传输的数据量可是大大减少了遍历绑定的工作转移到了客户端,大大减轻了服务端的压力。

jTemplates是一个基于JQuery的模板引擎插件,功能强大,有了他你就再不用为使用JS绑定数据时发愁了。后端语言使用php,asp.net,jsp等都不是问题,使用模板渲染可以很大程度上提高程序性能,使用异步获取数据,不用整个页面都回发,好处当然不仅仅是这些。

jTemplates能免费应用于商业和非商业。下载地址:http://jtemplates.tpython.com

2.jTemplate库下载

在这里插入图片描述
在项目中引入JS库,值得注意的是jquery.jtemplates依赖于jquery,所以引入的顺序有些要求:
我这里使用的是jquery-3.4.1,你可以在这里下载http://www.jquery.com/

引入js文件代码如下:

<script type="text/javascript" src="./js/jquery-3.4.1"></script>
<script type="text/javascript" src="./js/jquery-jtemplates.min.js"></script>

3.jTemplate简单案例

3.1.构造数据

jtemplates模板的简单使用,首先使用jtemplates就要使用json数据,在这里我们不妨构造一个json格式的数据,如下:

 <script type="text/javascript">
        $(document).ready(function () {
            //初始化JSON数据
            var data = {
                name: '用户列表',
                list_id: '编号89757',
                table: [
                    {id: 1, name: 'Rain', age: 22, mail: '[email protected]'},
                    {id: 2, name: '皮特', age: 24, mail: '[email protected]'},
                    {id: 3, name: '卡卡', age: 20, mail: '[email protected]'},
                    {id: 4, name: '戏戏', age: 26, mail: '[email protected]'},
                    {id: 5, name: '一揪', age: 25, mail: '[email protected]'}
                ]
            };
            // 附上模板
            $("#result1").setTemplateElement("template");
            // 给模板加载数据
            $("#result1").processTemplate(data);
        });
    </script>

3.2.模板内容

<!-- 模板内容 -->
<textarea id="template" style="display:none">
      <strong>{$T.name} : {$T.list_id}</strong>
      <table>
           <tr>
             <th>编号</th>
             <th>姓名</th>
             <th>年龄</th>
             <th>邮箱</th>
       </tr>
       {#foreach $T.table as record}
       <tr>
         <td>{$T.record.id}</td>
         <td>{$T.record.name}</td>
                       <td>{$T.record.age}</td>
         <td>{$T.record.mail}</td>
       </tr>
       {#/for}
      </table>
</textarea>

这个是我要最终显示的效果,也就是模板,然后模板定义好了,然后我们在定义一个最后用来承载显示数据的标签,一般用div或者其他标签均可,我这里使用div如下:

3.3.输出元素

<!-- 输出元素 -->
<div id="result1" ></div>

3.4.运行结果

在这里插入图片描述

小结:jTemplates的工作方式:1、setTemplate 指定可处理的模版对象 2、processTemplate 对模版化的对象进行数据处理

4.jTemplate简单案例-Ajax实现

4.1.新建一个JSON文件

{
  "name": "用户列表",
  "list_id": "1111",
  "table": [
    {
      "id": 1,
      "name": "Rain",
      "age": 22,
      "mail": "[email protected]"
    },
    {
      "id": 2,
      "name": "皮特",
      "age": 24,
      "mail": "[email protected]"
    },
    {
      "id": 3,
      "name": "卡卡",
      "age": 20,
      "mail": "[email protected]"
    },
    {
      "id": 4,
      "name": "戏戏",
      "age": 26,
      "mail": "[email protected]"
    },
    {
      "id": 5,
      "name": "一揪",
      "age": 25,
      "mail": "[email protected]"
    }
  ]
}

4.2.通过AJAX方式获取数据,并将数据填充到模板页中

 <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
 <script type="text/javascript" src="js/jquery.jtemplates.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("data.json",function (data) {
                //alert(JSON.stringify(result));
                // 附上模板
                $("#result1").setTemplateElement("template");
                // 给模板加载数据
                $("#result1").processTemplate(data);
            })
        });
    </script>

4.3.模板内容

<!-- 模板内容 -->
<textarea id="template" style="display:none">
      <strong>{$T.name} : {$T.list_id}</strong>
      <table>
           <tr>
             <th>编号</th>
             <th>姓名</th>
             <th>年龄</th>
             <th>邮箱</th>
       </tr>
       {#foreach $T.table as record}
       <tr>
         <td>{$T.record.id}</td>
         <td>{$T.record.name}</td>
                       <td>{$T.record.age}</td>
         <td>{$T.record.mail}</td>
       </tr>
       {#/for}
      </table>
</textarea>

这个是我要最终显示的效果,也就是模板,然后模板定义好了,然后我们在定义一个最后用来承载显示数据的标签,一般用div或者其他标签均可,我这里使用div如下:

4.4.输出元素

<!-- 输出元素 -->
<div id="result1" ></div>

4.5.运行结果

在这里插入图片描述

5.jTemplate基础语法

1、大括号{..} ,在这里面可以写任何javascript的代码,比如 {$T.toUpperCase()}
2、{$T} : 表示数据,例如上面的例子,$T.table表示得到data的table对象,$T.TotalCount 为 64。
3、{#foreach} : 循环获取数据,如上面:{#foreach $T.table as row}      {$T.row.Title}      {/for}  

jTemplates包含三个预定全局变量,分别是$T、$P、$Q。$T为模板提供数据调用功能,$P为模板提供参数变量调用功能,$Q.version提供当前jTemplate的版本
jTemplates还支持#if、#for、#cycle、#foreach、#include、#param标签,帮助你处理实现复杂的业务情形。 

5.1 IF语法

语法格式:

{#if |COND|}..{#elseif |COND|}..{#else}..{#/if}

示例:

#if 示例:
{#if $T.hello} hello world. {#/if}
{#if 2*8==16} good {#else} fail {#/if}
{#if $T.age>=18)} 成人了 {#else} 未成年 {#/if}
{#if $T.list_id == 3} System list {#elseif $T.list_id == 4} Users List {#elseif $T.list_id == 5} Errors list {#/if}

5.2 for 语法

#for 语法

{#for |VAR| = |CODE| to |CODE| [step=|CODE|]}..{#else}..{#/for}
或
{#for |variable| = |start| to |end| [step=|stepBy|]}..{#else}..{#/for}
#for 示例:
默认步长:{#for index = 1 to 10} {$T.index} {#/for} 
正向步长:{#for index = 1 to 10 step=3} {$T.index} {#/for}
负向步长及空循环:{#for index = 1 to 10 step=-3} {$T.index} {#else} nothing {#/for}
也可以在循环中使用变量:{#for index = $T.start to $T.end step=$T.step} {$T.index} {#/for}
说明:{#else}是在{#for...}未能执行的时的输出内容。

5.3 foreach 语法

#foreach 语法


#foreach 示例:
默认:{#foreach $T.table as record} {$T.record.name} {#/for}
指定起始位置:{#foreach $T.table as record begin=1} {$T.record.name} {#/for}
指定起始和循环次数:{#foreach $T.table as record begin=1 count=2} {$T.record.name} {#/for}
指定步长:{#foreach $T.table as record step=2} {$T.record.name} {#/for}
#foreach 内定环境变量:
$index - index of element in table
$iteration - id of iteration (next number begin from 0)
$first - is first iteration?
$last - is last iteration?
$total - total number of iterations
$key - key in object (name of element) (0.6.0+)
$typeof - type of element (0.6.0+)
#foreach 示例所需要的数据:
var data = {
name: 'User list',
list_id: 4,
table: [
{id: 1, name: 'Anne', age: 22, mail: '[email protected]'},
{id: 2, name: 'Amelie', age: 24, mail: '[email protected]'},
{id: 3, name: 'Polly', age: 18, mail: '[email protected]'},
{id: 4, name: 'Alice', age: 26, mail: '[email protected]'},
{id: 5, name: 'Martha', age: 25, mail: '[email protected]'}
]
};
(0.7.0+)版以后新增的功能,支持待循环集合用函数代替:
{#foreach |FUNC| as |NAME| [begin=|CODE|] [end=|CODE|] [count=|CODE|] [step=|CODE|]}..{#else}..{#/for}
例:
f = function(step) {
if(step > 100) return null; // stop if loop is too long
return "Step " + step;
};

$("#result").setTemplate("{#foreach f as funcValue begin=10 end=20} {$T.funcValue}<br/> {#/for}");
$("#result").processTemplate();
#foreach在每次循环时请求的就是f函数,然后传递参数给f使用,并返回结果给funcValue变量

5.4 cycle 语法

#cycle 语法

{#cycle values=|ARRAY|}
功能:提供周期性的调用,在循环中实现交替样式功能时可用到
示例:
{#cycle values=[1,2,3,4]}
下面模板在执行循环时,就会周期性的调用#cycle数组中的值,这样就能实现行交替的效果:
<table width=\"200\">
{#foreach $T.table as row}
<tr bgcolor=\"{#cycle values=['#AAAAAA','#CCCCCC']}\">
<td>{$T.row.name.link('mailto:'+$T.row.mail)}</td>
</tr>
{#/for}
</table>

5.5 include 语法

#include 语法

{#include |NAME| [root=|VAR|]}
功能:提供子模板调用
示例:
{#template MAIN}
{* this is comment *}
{$T} {* $T == $T.toSource() *}
<table>
{#foreach $T.table as record}
{#include ROW root=$T.record}
{#/for}
</table>
{#/template MAIN}

{#template ROW}
<tr class="values=['bcEEC','bcCEE']} {#cycle">
<td>{$T.name}</td>
<td>{$T.mail}</td>
</tr>
{#/template ROW}
说明:{#template MAIN} 是指定模板的主要部分,必不可少。
{#template ROW}是定义一个名为“ROW”的子模板。
{#include ROW root=$T.record}是主模板调用“ROW”子模板,并传递参数$T.record

5.6.param 语法

#param 语法 

{#param name=|NAME| value=|CODE|}
功能:定义模板内的局部变量参数,使用$P调用。
示例:
$("#result").setTemplate("{#param name=x value=888}{$P.x}");
$("#result").processTemplate();
输出结果:888
示例:
$("#result").setTemplate("{#param name=x value=$P.x+1}{$P.x}");
$("#result").setParam('x', 777);
$("#result").processTemplate();
输出结果:778
示例:
$("#result").setTemplate("<ul>{#foreach $T.table as row}<li>{$P.x} {$T.row.name}</li>{#param name=x value=$P.x+3}{#/for}<ul>");
$("#result").setParam('x', 1);
$("#result").processTemplate(data);
需要数据:
var data = {
name: 'User list',
list_id: 4,
table: [
{id: 1, name: 'Anne', age: 22, mail: '[email protected]'},
{id: 2, name: 'Amelie', age: 24, mail: '[email protected]'},
{id: 3, name: 'Polly', age: 18, mail: '[email protected]'},
{id: 4, name: 'Alice', age: 26, mail: '[email protected]'},
{id: 5, name: 'Martha', age: 25, mail: '[email protected]'}
]
};
输出结果:
# 1 Anne
# 4 Amelia
# 7 Polly
# 10 Alice
# 13 Martha

6.jTemplate案例

案例1:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>JTemplates模板测试demo01</title>
        <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-jtemplates.js"></script>
  
        <script type="text/javascript">
            $(document).ready(function () {
                //初始化JSON数据
                var jsonData = {
                    name : '用户列表',
                    list_id : '070101061',
                    table : [
                        {id: 1, name: '马韶华', age: 22, mail: '[email protected]'},
                        {id: 2, name: '皮特', age: 24, mail: '[email protected]'}, 
                        {id: 3, name: '卡卡', age: 20, mail: '[email protected]'}, 
                        {id: 4, name: '戏戏', age: 26, mail: '[email protected]'}, 
                        {id: 5, name: '一揪', age: 25, mail: '[email protected]'}
                    ]
                };
                //附加模板
                $("#result").setTemplateElement("jTemplates");
                //给模板加载数据
                $("#result").processTemplate(jsonData);
            });
  
        </script>
    </head>
  
    <body>
        <!-- 模板内容 -->
        <textarea id="jTemplates" style="display:none">
            <strong>{$T.name} : {$T.list_id}</strong>
            <table border=1>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>邮箱</th>
                </tr>
                {#foreach $T.table as record}
                <tr>
                    <td>{$T.record.id}</td>
                    <td>{$T.record.name}</td>
                    <td>{$T.record.age}</td>
                    <td>{$T.record.mail}</td>
                </tr>
                {#/for}
            </table>
        </textarea>
  
        <div id="result" />
  
    </body>
</html>

案例2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>JTemplates模板测试demo02</title>
        <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-jtemplates.js"></script>
        <link rel="stylesheet" href="css/style.css" />
        <script type="text/javascript">
            $(document).ready(function () {
                $("#CustomersList").setTemplateElement("jTemplates_list");
                $("#CustomersList").setParam("year", "2012");
                $("#CustomersList").processTemplateURL("js/data.json");
  
                $("#CustomerDetails").setTemplateElement("jTemplates_details");
            });
  
            function showDeatils(cust) {
                $("#CustomerDetails").processTemplate(cust);
            }
  
        </script>
    </head>
  
    <body>
        <!-- 模板内容 -->
        <textarea id="jTemplates_list" style="display:none">
            {#template MAIN}
                <table>
                    <tr class="color:{#cycle values=['#ffffff', '#dddddd']}">
                        <td class="header">Details</td>
                        <td class="header">Name</td>
                        <td class="header">Age</td>
                    </tr>
                    {#foreach $T.Customers as Customer}
                        {#include ROW root=$T.Customer}
                    {#/for}
                </table>
            {#/template MAIN}
  
            {#template ROW}
                <tr class="color:{#cycle values=['#ffffff', '#dddddd']}">
                    <td><a href="#" onclick="showDeatils({#var $T})">选择</td>
                    <td>{$T.FirstName} - {$T.LastName}</td>
                    <td>{$P.year} - {$T.Born}</td>
                </tr>
            {#/template ROW}
        </textarea>
  
        <textarea id="jTemplates_details" style="display:none">
            <table>
                <tr><td class="header">First Name</td><td>{$T.FirstName}</td></tr>
                <tr><td class="header">Last Name</td><td>{$T.LastName}</td></tr>
                <tr><td class="header">Born</td><td>{$T.Born}</td></tr>
                <tr><td class="header">E-mail</td><td>{$T.Email.link('mailto:'+$T.Email)}</td></tr>
            </table>
        </textarea>
  
        <!-- Output elements -->
        <div id="CustomersList" class="Content"></div>
        <div id="CustomerDetails" class="Content"></div>
    </body>
</html>

案例3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>JTemplates模板测试demo03</title>
        <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-jtemplates.js"></script>
        <link rel="stylesheet" href="css/style.css" />
        <script type="text/javascript">
            $(document).ready(function () {
  
                $.getJSON('js/data.json', function(data) {
                    var Items = data.Items;
                    var Bom = Items[0].BOM; //sample data
                    $("#ItemBOM").setTemplateElement("jTemplates_list");
                    $("#ItemBOM").processTemplate(Bom);
                });
            });
  
        </script>
    </head>
  
    <body>
        <!-- 模板内容 -->
        <textarea id="jTemplates_list" style="display:none">
            {#template MAIN}
                <h3>BOM : {$T.Name}</h3>
                <div>
                    {#include ROW root=$T.Elements}
                </div>
            {#/template MAIN}
  
            {#template ROW}
                <ul>
                    {#foreach $T as entry}
                        <li>{$T.entry.Name} - {$T.entry.Qty}</li>
                        {#if $T.entry.Elements}
                            {#include ROW root=$T.entry.Elements}
                        {#/if}
                    {#/for}
                </ul>
            {#/template ROW}
        </textarea>
  
        <!-- Output elements -->
        <div id="ItemBOM" class="Content"></div>
    </body>
</html>

案例4:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>JTemplates模板测试demo03</title>
        <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
        <script type="text/javascript" src="js/jquery-jtemplates.js"></script>
        <link rel="stylesheet" href="css/style.css" />
        <script type="text/javascript">
            var customers = null;
            var items = null;
            var salesEntry = null;
            $(document).ready(function () {
                $.getJSON("js/data.json", function (data) {
                    customers = data.Customers;
                    items = data.Items;
                    salesEntry = data.SalesEntry;
  
                    $("#customers").setTemplateElement("template_list_customers");
                    $("#customers").processTemplate(customers);
  
                    $("#items").setTemplateElement("template_list_items").processTemplate(items);
                    $("#entries").setTemplateElement("template_list_entries").processTemplate(null);
                });
  
            });
  
            function updateCustomer(customer, index) {
                customers[index].selected = customer.checked;
                updateEntries();
            }
  
            function updateItem(item, index) {
                items[index].selected = item.checked;
                updateEntries();
            }
  
            function updateEntries() {
                var custCacheMap = {};
                var itemCacheMap = {};
  
                for(var i=0; i<customers.length; ++i) {
                    custCacheMap[customers[i].ID] = customers[i];
                }
  
                for(var i=0; i<items.length; ++i) {
                    itemCacheMap[items[i].ID] = items[i];
                }
  
                var entries = $.map(salesEntry, function (e) {
                    var cust = custCacheMap[e.CustomerID];
                    var item = itemCacheMap[e.ItemID];
  
                    if(cust == null || item == null) {
                        return null;
                    }
  
                    if(cust.selected && item.selected) {
                        return [{
                            "CustName": cust.FirstName + ' ' + cust.LastName,
                            "ItemName": item.Name,
                            "Price": e.SalesPrice,
                            "Cost": e.UnitCost
                        }];
                    } else {
                        return null;
                    }
                });
  
                $("#entries").processTemplate(entries);
            }
  
        </script>
    </head>
  
    <body>
        <!-- 模板内容 -->
        <p style="display:none;">
            <textarea id="template_list_customers" rows="0" cols="0">
                <div class="title">Customers</div>
                <table>
                    <tr style="values=['yellow', 'green']}">
                        <td class="header">Choose</td>
                        <td class="header">Name</td>
                    </tr>
                    {#foreach $T as record}
                    <tr style="values=['yellow', 'green']}">
                        <td><input type="checkbox" value="{$T.record.ID}" onclick="updateCustomer(this, {$T.record$index})"></td>
                        <td>{$T.record.FirstName} {$T.record.LastName}</td>
                    </tr>
                    {#/for}
                </table>
            </textarea>
        </p>
  
        <p style="display:none">
            <textarea id="template_list_items" rows="0" cols="0">
                <div class="title">Items</div>
                <table>
                    <tr style="values=['yellow', 'green']}">
                        <td class="header">Choose</td>
                        <td class="header">Name</td>
                    </tr>
                    {#foreach $T as record}
                    <tr style="values=['yellow', 'green']}">
                        <td><input type="checkbox" value="{$T.record.ID}" onclick="updateItem(this, {$T.record$index})"></td>
                        <td>{$T.record.Name}</td>
                    </tr>
                    {#/for}
                </table>
            </textarea>
        </p>
  
        <p style="display:none;">
            <textarea id="template_list_entries" rows="0" cols="0">
                <div class="title">Entries</div>
                <table>
                    <tr>
                        <td class="header">Customer</td>
                        <td class="header">Item</td>
                        <td class="header">Price</td>
                        <td class="header">Cost</td>
                        <td class="header">Profit</td>
                    </tr>
                    {#param name=totalNum value=0}
                    {#foreach $T as record}
                    <tr style="values=['yellow', 'green']}">
                        <td>{$T.record.CustName}</td>
                        <td>{$T.record.ItemName}</td>
                        <td>{$T.record.Price}</td>
                        <td>{$T.record.Cost}</td>
                        <td>{$T.record.Price - $T.record.Cost}</td>
                    </tr>
                    {#param name=totalNum value=$P.totalNum + ($T.record.Price - $T.record.Cost)}
                    <tr>
                        <td class="header"></td>
                        <td class="header"></td>
                        <td class="header"></td>
                        <td class="header">Total:</td>
                        <td class="header">{$P.totalNum}</td>
                    </tr>
                    {#/for}
                </table>
            </textarea>
        </p>
  
        <div id="customers"></div>
        <div id="items"></div>
        <div id="entries"></div>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/BruceLiu_code/article/details/102650249