2012-06-23 47 views
5

我正在閱讀有關Mustache.js的模板。我不明白的是如何放置模板。我不會在同一個文件中拒絕他們。使用外部模板的小鬍子

$.get('test.htm', function(templates) { 
    // Fetch the <script /> block from the loaded external 
    // template file which contains our greetings template. 
    var template = $(templates).filter('#tpl-greeting').html(); 
    $('body').append(Mustache.render(template, templateData)); 
}); 


//test.htm 
<script id="tpl-greeting" type="text/html"> 
<dl> 
    <dt>Name</dt> 
    <dd>{{name}}</dd> 
    <dt>Time</dt> 
    <dd>{{timeNow}}</dd> 
</dl> 
</script> 

我必須創建一個控制器,返回我的模板或我可以參考嗎?

回答

6

有幾種方法可以做到這一點。

  1. 如果您使用的是服務器端腳本語言如PHP,只是它們包括在一個單獨的.mst(擴展名可能是你真正想要的東西)的JS內提交。例如, var _templateName = <?= JS::mustache('content/templateName.mst') ?>;。因此,當JS被實際渲染時,它將以標記呈現,但代碼仍然可以維護。此外,採用這種方法,如果您使用CDN,您的網站將受益於緩存的JS。
  2. 另一種方法是使用jQuery的$.get,$.getJSON等方法加載外部HTML文件。這個更詳細的實現是given here
+0

謝謝您的回答,但後來我不明白我的意思。爲什麼不讓控制器返回一個「填充的」html並且做一個$(「#old」)。replaceWith(「#new」); – pethel

+1

@ user874774你絕對可以。但是您仍然需要構造新的HTML w/new Data值以在replaceWith方法中使用。模板爲你做這件事,再加上使用模板可以保證一致性和清潔度。 – Swordfish0321

1

您可以將模板放在單獨的文件中,就像使用CSS和JS一樣。您可以使用Chevron從文件中加載外部模板,像這樣:

你加在你模板的鏈接到你的模板文件:

<link href="path/to/template.mustache" rel="template" id="templateName"/> 

然後,在你JS,你可以使你的模板,像這樣:

$("#templateName").Chevron("render", {name: "Slim Shady"}, function(result){ 
    // do something with 'result' 
    // 'result' will contain the result of rendering the template 
    // (in this case 'result' will contain: My name is Slim Shady) 
}); 

雪佛龍的文檔會舉些例子