9

私はmustache.jsを初めて使用しています。私が見つけたすべての例は、すべてをインライン化することについて話しているようですが、複数の場所で使用できるように、テンプレートを外部ファイルに入れたいと思います。それ、どうやったら出来るの?(違いが生じる場合は、スタックにjQueryがあります。)

だから私が持っていると言う:

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

1 に答える 1

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>
于 2010-12-10T20:37:36.187 に答える