jTemplates模板学习笔记

1、jTemplates工作方式

 

    1)setTemplateElement:指定可处理的模板对象

    2)processTemplate:对模板化的对象进行数据处理

2、语法解析

 

    1)jTemplates包含了三个预定义全局变量:$T$P$Q

 

         $T:为模板提供数据调用功能

         $P:为模板提供参数变量调用功能

         $Q:$Q.version提供当前jTemplates的版本

    2)jTemplates标签

    【#if】标签 

#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}

 

    【#foreach】标签

{#foreach |VAR| as |NAME| [begin=|CODE|] [count=|CODE|] [step=|CODE|]}..{#else}..{#/for}
#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: 'anne@domain.com'},
{id: 2, name: 'Amelie', age: 24, mail: 'amelie@domain.com'},
{id: 3, name: 'Polly', age: 18, mail: 'polly@domain.com'},
{id: 4, name: 'Alice', age: 26, mail: 'alice@domain.com'},
{id: 5, name: 'Martha', age: 25, mail: 'martha@domain.com'}
]
};
(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变量

 

    【#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>

 

    【#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

 

    【#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: 'anne@domain.com'},
{id: 2, name: 'Amelie', age: 24, mail: 'amelie@domain.com'},
{id: 3, name: 'Polly', age: 18, mail: 'polly@domain.com'},
{id: 4, name: 'Alice', age: 26, mail: 'alice@domain.com'},
{id: 5, name: 'Martha', age: 25, mail: 'martha@domain.com'}
]
};
输出结果:
# 1 Anne
# 4 Amelia
# 7 Polly
# 10 Alice
# 13 Martha

 

    案例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: '616059480@qq.com'},
                        {id: 2, name: '皮特', age: 24, mail: 'cssrain@domain.com'}, 
                        {id: 3, name: '卡卡', age: 20, mail: 'cssrain@domain.com'}, 
                        {id: 4, name: '戏戏', age: 26, mail: 'cssrain@domain.com'}, 
                        {id: 5, name: '一揪', age: 25, mail: 'cssrain@domain.com'}
                    ]
                };
                //附加模板
                $("#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>
posted @ 2015-10-30 13:39  Delena  阅读(1097)  评论(0编辑  收藏  举报