簡體   English   中英

如何在HTML中定義胡子部分?

[英]How to define mustache partials in 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文件中定義它們嗎?

我假設你正在使用Mustache的JS風格。

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

你需要:

  1. 為名稱定義一些虛擬數據
  2. 獲取#li-templ的HTML獲取部分模板
  3. 創建一個名為partial(li-templ)的對象作為鍵
  4. 告訴Mustache使用包含部分視圖數據的每個模板進行渲染

這里有一些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的所有工作 - http://jsfiddle.net/maxbeatty/EYDfP/

ICanHaz.js (ICH)可以幫助您解決這個問題。

ICanHaz.js :使用Mustache.js進行客戶端模板化的簡單/強大方法。

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

查看此ICH pull請求,從服務器自動加載<script type="text/html" src="my-templates.html"></script>到每個文件一個模板。

您還可以使用以下簡單代碼為每個遠程HTML文件加載多個模板

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM