2011-11-10 44 views
25

這是我的html:如何在HTML中定義鬍鬚部分?

<script type="text/html" id="ul-template"> 
    <ul id="list"> 
     {{> li-templ}} 
    </ul> 
</script> 

<script type="text/html" id="ul-template2"> 
    <div id="list2"> 
     {{> li-templ}} 
    </div> 
</script>  

<script type="text/html" id="li-templ"> 
    <p>{{ name }}</p> 
</script> 

,你可以看到,我想重用#li-templ一部分,但似乎我必須把它寫入到一個名爲li-templ.mustache文件,然後我可以把它作爲partial
我可以在單個html文件中定義它們嗎?

回答

28

我假設你使用鬍子的JS風味。

在mustache.js中,部分對象可以作爲第三個參數傳遞給Mustache.render。該對象應該以部分名稱爲鍵,其值應該是部分文本。

您需要:

  1. 定義一些虛擬的數據名稱
  2. 通過獲取#鋰TEMPL的HTML讓你的局部模板
  3. 與部分的名稱創建一個對象(li-templ)作爲密鑰
  4. 告訴小鬍子使用視圖數據呈現每個模板,包括您的部分

下面是一些jQuery來做到這一點:

var view = {"name" : "You"}, 
li = $('#li-templ').html(), 
partials = {"li-templ": li}, 
ul1 = Mustache.to_html($('#ul-template').html(), view, partials), 
ul2 = Mustache.to_html($('#ul-template2').html(), view, partials);; 

document.write(ul1, ul2); 

下面是它的jsfiddle所有working- http://jsfiddle.net/maxbeatty/EYDfP/

+5

你好,這是值得注意的是'Mustache.to_html'已經被替換爲'Mustache.render'(函數定義保持不變) – Matt

+0

難道只是我,或者是以下中的嵌入式這樣的模板鏈接谷歌博特?難道是由於TYPE =「text/html的」條目?會是使用類似的結果:type =「text/mustache-template」? – pointernil

+0

由於Mustache是​​來自github,因爲MIME類型是文本,所以沒有更多的執行,[這裏](http://jsfiddle.net/anandchakru/19z7gf6n/)是一個修改的小提琴,以防有人想要參考。 –

5

ICanHaz.js(ICH)可以幫助您與此有關。

ICanHaz.js:做客戶端模板與Mustache.js一個簡單/強大的方法。

我發現,在我的代碼編輯器的頁面混亂普通HTML混合模板(腳本標籤)(語法高亮,縮進等等)。作爲一個單獨的服務器加載它們可以保持HTML清潔。

檢出this ICH pull request for automatic loading of <script type="text/html" src="my-templates.html"></script> from your server爲每個文件一個模板。使用

你也可以load more than one template per remote HTML file this簡單的代碼,如:

function getTemplates(url) { 
    $.get(url, function (response) { 
     $('template', response).each(function() { 
      ich.addTemplate(this.id, $(this).text()); 
     }); 
    }); 
} 

或者,如果你想ICH從在您的網頁網址自動加載它們:

<head> 
    <link rel="templates" type="text/html" href="my-templates.html"> 
</head> 
$("link[type=templates]").each(function (index, link) { 
    getTemplates(link.attr("href")); 
}); 

在你my-templates.html

<templates> 
    <template id="ul-template"> 
     <ul id="list"> 
      {{> li-templ}} 
     </ul> 
    </template> 

    <template id="ul-template2"> 
     <div id="list2"> 
      {{> li-templ}} 
     </div> 
    </template>  

    <template id="li-templ"> 
     <p>{{ name }}</p> 
    </template> 
</templates>