JsRender for object 文法說明

來源:互聯網
上載者:User

標籤:style   blog   color   ar   java   for   sp   strong   div   

     JsRender 作為一款JavaScript模版引擎,必不可少的會有迴圈功能,也就是for,但由於JsRender過於靈活,for竟然可以接受object作為迴圈對象。

     {{for Array}}和{{for Object}}都是允許的,{{for Array}}大家都能理解,就是遍曆一個數組,逐個取出每個元素。但{{for Object}}就有點讓人匪夷所思了,而且官方文檔只是舉了個沒什麼協助的例子,其他無任何說明。

     剛開始小菜以為{{for Object}}的用意是遍曆該Object的所有屬性,但仔細一想,這個功能{{props Object}}已經實現了,props標籤的作用就是遍曆Object所有屬性,有多少個屬性,就迴圈多少次,每次迴圈都會有兩個隱藏的屬性:key,prop,key代表屬性名稱,prop代表屬性值,用起來非常方便。

     實際上,{{for Object}}並不是迴圈,它可以理解成進入(Into),也就是說進入到Object環境中,把當前的上下文設定為Object,類似於Handlebars.js中的with。

     舉個例子:

data:

 1 { 2   "title": "The A team", 3   "members": [ 4     { 5       "name": "Pete", 6       "city": "members_city", 7       "address": { 8         "city": "address_city", 9         "city1": "address_city1",10         "city2": "address_city2"11       }12     }13   ]14 }

template markup:

1 {{for members}}2   {{for address}}3     <p>.{{:city}}</p>4   {{/for}}5 {{/for}}

result:

1 address_city

 

     從結果可以看出,雖然members的item下也有city屬性,但由於通過{{for address}}進入到了address指向的Object中,{{:city}}直接從address中擷取了。

     同時,address有三個屬性,但結果只輸出了一行,證明{{for Object}}是不會迴圈的,僅僅是切換一下this。

 

JsRender for object 文法說明

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.