Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 external 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>
like image 838
sprugman Avatar asked Dec 10 '10 20:12

sprugman


1 Answers

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>
like image 77
DaveN Avatar answered Nov 12 '22 22:11

DaveN