开发者

how do I get my mustache.js template file included?

开发者 https://www.devze.com 2023-01-30 04:30 出处:网络
I\'m working with mustache.js for the first time. All the examples I\'m finding seem to talk about putting everything inline, but I want my templates in extern开发者_JAVA百科al files so they can be us

I'm working with mustache.js for the first time. All the examples I'm finding seem to talk about putting everything inline, but I want my templates in extern开发者_JAVA百科al files so they can be used in multiple places. How do I do that? (I've got jQuery in my stack, if that makes a difference.)

So say I have:

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>


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

Where your template is in the 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> 

You could also render multiple templates directly into your page...

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

精彩评论

暂无评论...
验证码 换一张
取 消