前端模板引擎doT.js的用法

简介

一款简单好用的前端模板引擎

用法

<script type="text/javascript" src="js/doT.min.js"></script>

! 和 = 的用法与区别

<!--用户信息-->
<div class="ibBox yhxx" id="userInfo">
  <script id="userTemplate" type="text/x-dot-template">
     <div class="ibTitle">用户信息</div>
      <dl>
         <dd>
            <label><em>姓名:</em><span>{{!it.name}}</span></label>
            <label><em>工号:</em><span>{{=it.number}}</span></label>
           <label><em>机构:</em><span>{{!it.organName}}</span></label>
        </dd>
     </dl>
  </script>
</div>
<script>
    var data = {"name":"张三","number":1001,"organName":""},//要渲染的数据
    var userTemplate = doT.template($("#userTemplate").text());//生成模板
    $("#userInfo").html(userTemplate(data));//数据渲染
</script>

两者都是赋值,区别于 ! 无法渲染数值为0的数据,而 = 可以,不过 ! 可以渲染带编码的数据,比如

var data= {"url":"http://jq22.com/?keywords=Yoga","html":"<div style='background: #f00; height: 30px; line-height: 30px;'>html元素</div>"};

~ 的用法

{{~it.list:item:index}}
<tr data-id="{{!item.id}}">
    <td>{{!item.title}}</td>
    <td>{{!item.publishTime}} </td>
</tr>
{{~}}

用于循环数组

? 的用法

<span class="{{? it.type==1}}w1{{?? it.type==2}}w2{{??}}w3{{?}}">
  {{?it.status==0}}未发布{{??}}已发布{{?}}
</span>

条件判断,相当于if....else if......

# 的用法

<div class="ibBox yhxx" id="userInfo">
  <script id="userTemplate" type="text/x-dot-template">
    <!-- 定义模板tem1 -->
    {{## def.tem1:
      <label><em>姓名:</em><span>{{!it.name}}</span></label>
    #}}
     <div class="ibTitle">用户信息</div>
      <dl>
         <dd>
        <!-- 引用模板tem1 -->
            {{#def.tem1}}
            <label><em>工号:</em><span>{{=it.number}}</span></label>
           <label><em>机构:</em><span>{{!it.organName}}</span></label>
        </dd>
     </dl>
  </script>
</div>

格式:定义模板{{##def.name:******#}} name为模板名称,*****为模板内容,引用模板{{#def.name}} name为模板名称

for 原生循环的使用

{{ for(var i=0;i<it.length;i++){ }}
  {{ if(it[i].bz == 1){ }}
      {{#def.tem1}}
   {{ }else{ }}
     {{#def.tem2}}
  {{ } }}
{{ } }}
原文地址:https://www.cnblogs.com/Ly66310/p/11346505.html