doT.js模板引擎及基礎原理


個人bolg地址


時至今日,基於后端JavaScript(Node.js)和MVC思想也開始流行起來。模板引擎是數據和頁面分離工作中最重要的一環,在各大門戶網站均有利用到模板引擎。

模板引擎有很多種,但是原理了解也是非常必要的。

什么是模板引擎,其根本原理就是將數據轉換成“String”,再通過模板引擎抓取數據進行頁面數據渲染。 

看一個例子

1 <script type="template" id="template">
2     <h2>
3       <a href="{{href}}">
4         {{title}}
5       </a>
6     </h2>
7     <img src="{{imgSrc}}" alt="{{title}}">
8   </script>

這樣的方法類似Angular和Vue中雙向數據綁定。 {{ XXXX }} 是需要進行替換的數據。

var data = [
    {
      title: "我是標題1",
      href: "我是鏈接1",
      imgSrc: "我是圖片1.jpg"
    },
    {
      title: "我是標題2",
      href: "我是鏈接2",
      imgSrc: "我是圖片2.jpg"
    }
  ];

可以通過replace和正則的方法進行替換導入。

replace方法:

template = document.querySelector('#template').innerHTML,
result = document.querySelector('.result'),
attachTemplateToData;
 
// 將模板和數據作為參數,通過數據里所有的項將值替換到模板的標簽上(注意不是遍歷模板標簽,因為標簽可能不在數據里存在)。
attachTemplateToData = function(template, data) {
        var i = 0,
            len = data.length,
            fragment = '';
 
        // 遍歷數據集合里的每一個項,做相應的替換
        function replace(obj) {
            var t, key, reg;
       
       //遍歷該數據項下所有的屬性,將該屬性作為key值來查找標簽,然后替換
            for (key in obj) {
                reg = new RegExp('{{' + key + '}}', 'ig');
                t = (t || template).replace(reg, obj[key]);
            }
 
            return t;
        }
 
        for (; i < len; i++) {
            fragment += replace(data[i]);
        }
 
        return fragment;
    };
 
result.innerHTML = attachTemplateToData(template, data);

不用再次去特意設置變量名。  

 

 

doT.js模板引擎

1.   {{ = it.xxx }}  賦值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>   <!-- = 賦值-->
</head>
<body>
    <div id="interpolation"></div>
    <script id="interpolationtmpl" type="text/x-dot-template">  <!--script的ID是為了被doT模板引擎抓取語法和模板 type必須為該類-->
        <div>Hi {{=it.name}}!</div>  <!--it在模板里為數據源 it.name 等同於 dataInter.name -->
        <div>{{=it.age || ''}}</div> <!-- = 為賦值,如果不存在改數據,||'' 為空 -->
    </script>
</body>
<script src="./doT.js"></script>
<script src="./jquery.min.js"></script>

<script>
//定義數據源 var dataInter = {"name":"jake","age":31};
  // doT使用模板方法進行抓取script標簽里的模板語法和布局
var interText = doT.template($("#interpolationtmpl").text());
  // 將數據賦值給id對應的div進行渲染。 $(
"#interpolation").html(interText(dataInter)); </script> </html>

2.   {{ for }}  循環

   語法:  {{ for var KEY in DATA {  }}
                {{= key }}
                {{  }  }}

  

<body>
    <div id="evaluation"></div>
    <script id="evaluationtmpl" type="text/x-dot-template">
    {{ for(var prop in it) { }}
        <div>KEY:{{= prop }}--------VALUE:{{= it[prop] }}</div><!--將值進行賦值循環-->
    {{ } }}
    </script>

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

<script>
   var dataEval = {
"name":"Jake",
"age":31,
"interests":["basketball","hockey","photography"],"contact":{"email":"122@123.com","phone":"999999999"}
};
var evalText = doT.template($("#evaluationtmpl").text()); $("#evaluation").html(evalText(dataEval)); </script>

要注意 {{ for(var prop in it) { }}  ...  {{  } }}   為閉合標簽,是為了讓其中的模板進行輸出,以及讓{{ ... }} 的表達式進行執行。

可能這種語法很多小伙伴們看不懂,但是 改變一下

 for(var prop in it) {       
        <div>KEY:{{= prop }}--------VALUE:{{= it[prop] }}</div> <!--將循環進行賦值-->
     } 

把外面的花括號去掉了就能看懂了把。和上相比,只是將表達式都用雙花括號包圍起來,以便給doT模板引擎識別。
{{ for(var prop in it) { }} <div>KEY:{{= prop }}--------VALUE:{{= it[prop] }}</div><!--將值進行賦值循環-->  {{ } }}

 

3.   {{~it.array:value:index}}  數組數據

 語法:
     {{~data.array :value:index }}
       ...
     

<body>
    <div id="arrays"></div>
    <script id="arraystmpl" type="text/x-dot-template">
        {{~it.array:value:index}}  <-- ~ 為循環數組it.data -->
            <div>{{= index+1 }}{{= value}}</div>   <!--index為下標,初始值為0 ,可以進行計算-->
        {{~}}
    </script>
</body>
<script src="./doT.js"></script>
<script src="./jquery.min.js"></script>

<script>
   var dataArr = {"array":["banana","apple","orange"]};
   var arrText = doT.template($("#arraystmpl").text());
   $("#arrays").html(arrText(dataArr));
</script>

 

 

 

4.   {{ = it.xxx }}  賦值

 語法:

      {{? }} if
      {{?? }} else if
      {{??}} else

<body>   
    <div id="condition"></div>
    <script id="conditionstmpl" type="text/x-dot-template">

        {{? !it.name }}<!--if有數據就跳過-->
            <div>Oh, I love your name, {{=it.name}}!</div>
        {{?? it.age === 1}}<!-- else if (age=31)執行此 -->
            <div>當前值為{{= it.age}}</div>
        {{?? !(it.age === 0)}}<!-- else if (age不為0)執行此 -->
            <div>Guess nobody named you yet!</div>
        {{?? !it.age == 0)}}<!-- 0本身為false  所有age為true 取反 -->
            <div>Guess nobody named you yet!</div>
        {{??}}
             You are {{=it.age}} and still dont have a name?
        {{?}}

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

<script>
    var dataEncode = {"name":"yzw","age":1};
    var EncodeText = doT.template($("#conditionstmpl").text());
    $("#condition").html(EncodeText(dataEncode));
</script>

提示:!it.age  當age為0的時候為true,非0為false,但是進行數據恆等(===)的時候,

如果想要將數據的結果進行取反,必須加個括號!(it.age === 0)  當age為0  ,為false  不等於!it.age === 0;

 

 

模板引擎還是非常好用的,其余的{{for 插值 with encoding }}、{{##}}就不在本文敘述了,在使用過程中至今還未使用到。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM