art-template介紹


一、art-template介紹

  1. art-template 是一個簡約、超快的模板引擎。它采用作用域預聲明的技術來優化模板渲染速度,從而獲得接近 JavaScript 極限的運行性能,並且同時支持 NodeJS 和瀏覽器。
  2. 使用art-template也便於維護代碼,以前我們進行數據渲染的時候是通過字符串拼接然后再通過append的方式追加到數據源id上。
  3. 而用了模板引擎以后,我們只需要html文件中修改html內容。還有使用了模板引擎以后DOM操作的效率也會更高一點。
二、安裝和使用
  • 第一種方式是直接從官網下載對應的js文件
  • 第二種是 npm install art-template --save
三、相關代碼示例
 1 兩種定義模板方式用一個就可以了
 2 <div class="span_2 list_box">
 3     
 4 </div>
 5 
 6     <!-- 定義模板:原始語法 --><!---下面的list為js文件中渲染數據對象的屬性名,curr為遍歷數組元素對象時當前屬性值,i為當前索引-->
 7     <script type="text/html" id="list_temp2">
 8     <% for (var i = 0, len = list.length; i < len; i++) { var curr=list[i]; %>
 9     <div class="col_1_of_single1 span_1_of_single1">
10             <a href="/html/single.html">
11              <img src="<%= curr.img_url %>" class="img-responsive" alt=""/>
12              <h3><%= curr.title %></h3>
13              <p><%= curr.desc %></p>
14              <h4><%= curr.price %></h4>
15              </a>  
16         </div> 
17         <% } %>
18     </script>
19     <!-- 定義模板:標准語法(簡潔語法) -->
20     <script type="text/html" id="list_temp">
21     <!--這個list是js渲染數據對象的屬性名,curr是遍歷數組元素時用於代替list的,index是索引,即curr【index】為當前值代替list-->
22     {{ each list curr index }}
23     <div class="col_1_of_single1 span_1_of_single1">
24             <a href="/html/single.html">
25              <img src="{{ curr.img_url2 }}" class="img-responsive" alt=""/>
26              <h3>{{ curr.title }}</h3>
27              <p>{{ curr.desc }}</p>
28              <h4>{{ curr.price }}</h4>
29              </a>  
30         </div> 
31         {{ /each }}
32     </script>
33 
34 <!--js文件中使用requirejs引入需要的模塊包括art-template模塊(取的名字為template,這個模塊是在config文件中配置好的一個art-template短名稱),rap2模擬假數據,jquery獲取假數據以及將數據渲染至html文件中的.list_box中-->
35 require(["config"], function(){
36   require(["jquery", "template", "header", "footer"], function($, template, header){
37     <!--jquery中方法動態獲取列表頁面數據(模擬假數據)-->
38         $.getJSON("http://rap2api.taobao.org/app/mock/25320/api/list", function(data){
39     <!--這個template是art-templatede中有的函數,他有2個參數,第一個是script標簽的id,第二個參數是模板中需要循環遍歷的對象和其值-->
40             const html = template("list_temp2", {list : data.res_body.data});
41             $(".list_box").html(html);
42         })
43     });
44 });

 


免責聲明!

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



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