小台的IT备忘录  
脑子越来越不好用,只能依靠烂笔头了~
前言
     前后端开发分的越来越细化,为了方便前端工程师更好的调试后端工程师嵌套的代码,前后分离技术就出现了,简单理解其实就是Ajax异步将数据提供给JavaScript,由JavaScript进行迭代展现渲染成想要的效果,这样做还可以使页面数据异步化,页面展现时只需要加载页面结构及js、css、image等,而这些静态文件还可以通过CDN进行优化,缩短了打开页面白屏的时间,进一步加快了用户看到页面的速度,优点还是非常多的。
     前端MVVM框架有很多Vue.js、Angular2.js、React.js、juicer.js(ali)、artTemplate.js(tencent)、doT.js等等有很多,各有优势,前三个属于重量级功能大而全,而我的需求只需要简单迭代即可,所以选择后三个轻量级的,推荐使用juicer.js是阿里的而且支持Node.js,语法不太抽象很容易理解。
     无论那种框架实际应用时主要的功能就是循环、判断、输出这三个,下面我们根据日常需要撰写一下应用实例。
一、juicer的应用
官网地址:http://juicer.name/
1、基本语法
//变量输出${变量}
${var flag = "test"}

//变量避免转义输出$${变量}

//循环{@each}...{@/each}
{@each list as item}
     //do something...
     ${item.prop}
{@/each}
{@each list as item, index}
     //do something...
     ${index}
     //此处的index代表当前索引
{@/each}

//判断{@if}...{@/if}
{@if ${item.prop == 'a'}}
     //do something...
{@else if}
     //do something...
{@else}
     //do something...
{@/if}

//注释{# 内容}

//辅助循环{@each i in range(m, n)}
{@each i in range(5, 10)}
     ${i} //输出5 6 7 8 9
{@/each}

//嵌套模板{@include tpl, data}

 2、引入js文件

<script type="text/javascript" src="~/static/js/jquery/jquery-min.js"></script><!--可以不用jquery,使用默认js语法即可-->
<script type="text/javascript" src="~/static/js/juicer/juicer-min.js"></script>

3、设置自定义标签

不同开发语言可能导致对不同的模板符号编译错误,我们可以自定义模板符号规则
//页面加载后设置自定义标签
$(function () {
    juicer.set({
        'tag::operationOpen': '{*',     //操作标签-开
        'tag::operationClose': '}',     //操作标签-关
        'tag::interpolateOpen': '${',   //变量标签-开
        'tag::interpolateClose': '}',   //变量标签-关
        'tag::noneencodeOpen': '$${',   //禁止转义标签-开
        'tag::noneencodeClose': '}',    //禁止转义标签-关
        'tag::commentOpen': '{#',       //注释标签-开
        'tag::commentClose': '}',       //注释标签-关
        'cache': true,          //[默认开启]是否缓存模板编译结果,开启后会避免同一模板多次数据渲染时重复编译模板,减少编译模板所耗的时间
        'script': true,         //[默认开启]是否清除空白,清除模板中的空白,包括换行、回车等
        'error handling': true, //[默认开启]是否处理错误
        'detection': true       //[默认开启]是否检测变量是否定义,开启后如果变量未定义,将用空白字符串代替
    });
})

 4、编写展示模版

<script id="tplAccountAll" type="text/template">
    <thead>
        <tr class="bg-warning">
            <th class="text-center">账号</th>
            <th class="text-center">现金余额</th>
            <th class="text-center">冻结资金</th>
            <th class="text-center">账号描述</th>
            <th class="text-center">绑定手机</th>
            <th class="text-center">绑定邮箱</th>
            <th class="text-center">独立核算</th>
            <th class="text-center">状态</th>
            <th class="text-center">创建时间</th>
            <th class="text-center">操作</th>
        </tr>
    </thead>
    {*each list as item}
    <tr>
        <td class="text-primary">${item.AccountNo}</td>
        <td class="text-right text-success">${item.Balance.toFixed(2)}</td>
        <td class="text-right text-success">${item.FreezeBalance.toFixed(2)}</td>
        <td class="text-center">${item.AccountDescription}</td>
        <td class="text-center">${item.Mobile}</td>
        <td class="text-center">${item.Email}</td>
        <td class="text-center">${item.IsSelfFinanced}</td>
        <td class='${item.Status == 1 ? "text-success" : "text-danger"} text-center'>${item.StatusName}</td>
        <td class="text-center">${item.CreateTime}</td>
        <td class="text-center">
            {*if item.AccountNo != item.CustomerNo}
            <a href="javascript:void(0)" onclick="updateStatus('${item.AccountNo}',${item.Status}, this)">[${item.StatusOperation}]</a>
            {*/if}
            <a href="~/AccountManage/GrantRuleToAccount?AccountNo=${item.AccountNo}" target="_blank">[分配权限]</a>
            <a href="~/AccountManage/SetCreditLineLimit?AccountNo=${item.AccountNo}" target="_blank">[授信限额设定]</a>
            <a href="javascript:void(0)" onclick="showPayBusInfo('${item.AccountNo}')">[查看授信余额]</a>
        </td>
    </tr>
    {*/each}
</script>

5、渲染模版展示内容

<script type="text/javascript">
    $(function () {
        $.post("/AccountManage/AjaxGetAccountListData", function (data) {
            data = { list: JSON.parse(data) };
            console.log(data);
            //获取模版
            var tplAccountAll = $("#tplAccountAll").html();
            //渲染数据
            var htmlContent = juicer(tplAccountAll, data);
            //显示内容
            $("#showAccountAll").html(htmlContent);
        });
    })
</script>

 

二、doT的应用

 1、基本语法 
{{= }} for interpolation 输出
{{ }} for evaluation 代码块
{{~ }} for array iteration 迭代
{{? }} for conditionals 条件
{{! }} for interpolation with encoding 编码输出
{{# }} for compile-time evaluation/includes and partials
{{## #}} for compile-time defines

 2、引入js文件

<script src="jquery.min.js"></script>
<script src="doT.min.js"></script>

 3、编写展示模板

<script id="tmpBuyAndBuy" type="text/x-dot-template">
    {{ if(it && it.length > 0){ }}
        <div class="guessTit">
            <div class="guessLine abs"></div>
            <span class="abs w200">根据购物车的商品,为您推荐</span>
        </div>
        <div class="guseeBig">
            <p class="t2">90%的妈妈还买了以下商品</p>
        </div>
        <div class="guessLoveCon">
            <ul class="guessCon clearfix">
                {{ for(var i = 0; i < it.length; i++){ }}
                {{ var item = it[i]; }}
                <li>
                    <a href="{{=item.GoodsShowUrl}}">
                        <div class="hotProImg rel">
                            <img src="{{=item.GoodsImgUrl}}" alt="">
                            {{?item.NationPic}}
                            <div class="hotProflag abs"><img src="{{=item.NationPic}}" alt=""></div>
                            {{?}}
                        </div>
                        <div class="gupt">{{=item.SellingPoint}}</div>
                        <div class="guessProTit gray">{{=item.GoodsName}}</div>
                        <div class="guessMoney clearfix">
                            <span class="s1"><i>{{=item.GoodsPriceInteger}}</i>.{{=item.GoodsPriceDecimal}}</span>
                            <span class="s2">¥{{=item.MarketPrice.toFixed(2)}}</span>
                        </div>
                    </a>
                </li>
                {{ } }}
            </ul>
        </div>
    {{ } }}
</script>

4、渲染模版展示内容

<script type="text/javascript">
    var jsBuyAndBuy = jsBuyAndBuy || {};
    jsBuyAndBuy.GetData = function (goodsids) {
        if (goodsids) {
            $.post("/Cart/AjaxBuyAndBuy", { goodsIds: goodsids }, function (data) {
                //注入模板
                var evalText = doT.template($("#tmpBuyAndBuy").text());
                //填充内容
                $("#cntBuyAndBuy").html(evalText($.parseJSON(data)));
                //隐藏Loading
                $("#loadBuyAndBuy").hide();
            });
        }
    }   
</script>

 我这里只简单介绍一下使用方法,这些基本够我日常应用了,如果有更高难度的需求,还请查阅官方文档,此类模板使用方法都大同小异,学会一个其他的也就都会了,区别只有各自的语法标记不同而已。

posted on 2017-03-28 15:36  taiyonghai  阅读(1998)  评论(0编辑  收藏  举报