2010-12-10 10 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(); 
あなたが直接あなたのページに複数のテンプレートをレンダリングすることができ

<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> 

テンプレートはDOMである

... ...あなたのページ全体がテンプレートであった場合

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

ああ、あなたは可能性がおそらく$( 'body')を使用します。 – DaveN

+1

テンプレートは外部ファイルにあります!それは全体のポイントです。私はそれを得るためにアヤックスの呼び出しを行うことができたと思うが、私はよりよい方法があるかどうか疑問に思っている.... – sprugman

+2

ああ、ああ、私はそれを取得するAJAXとonSuccessは、 – DaveN

関連する問題