2010-12-10 43 views
9

我正在第一次使用mustache.js。我发现的所有示例似乎都是关于将所有内容放在一起,但我希望我的模板位于外部文件中,以便可以在多个位置使用它们。我怎么做? (我有jQuery的在我的筹码,如果有差别)如何获得我的mustache.js模板文件?

所以说我有:

template.html

{{title}} spends {{calc}} 

data.js

var data = { title: "Joe", calc: function() { return 2 + 4; } }; 

index.html

<script type="text/javascript" src="data.js"></script> 

<div id="target"></div> 

<script type="text/javascript"> 
    var template = ?????? // how do I attach the template? 
    var html = Mustache().to_html(template, data); 
    $('#target')[0].innerHTML = html; 
</script> 

回答

1
template = $('.template').val(); 

如果您的模板是在DOM ...

<textarea class="template"> 
<h1>{{header}}</h1> 
{{#bug}} 
{{/bug}} 

{{#items}} 
    {{#first}} 
    <li><strong>{{name}}</strong></li> 
    {{/first}} 
    {{#link}} 
    <li><a href="{{url}}">{{name}}</a></li> 
    {{/link}} 
{{/items}} 

{{#empty}} 
    <p>The list is empty.</p> 
{{/empty}} 
</textarea> 

你也可以使多个模板直接到您的网页...

<script id="yourTemplate" type="text/x-jquery-tmpl"> 
    {{tmpl "#yourTemplate"}} 
    <div>Something: ${TemplateValue}</div> 
</script> 
+0

哦,如果你的整个页面模板你可以可能使用$('body')。val(); – DaveN 2010-12-10 20:38:37

+1

但模板在外部文件!这就是整个问题。我想我可以做一个Ajax调用来获得它,但我想知道是否有更好的方法.... – sprugman 2010-12-10 20:46:27

+2

啊好吧,是的,我想AJAX出来得到它和onSuccess分配响应模板变种。 – DaveN 2010-12-10 20:56:14