2012-06-23 102 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) 
}); 

雪佛龙的文档会举些例子