9

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>

1 Answer 1

1
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>
4
  • Oh, if your entire page was the template you could probably use $('body').val(); Commented Dec 10, 2010 at 20:38
  • 1
    But the template is in an external file! that's the whole point. I guess I could make an ajax call to get it, but I'm wondering if there's a better way....
    – sprugman
    Commented Dec 10, 2010 at 20:46
  • 2
    Ah ok, yep, I'd AJAX out to get it and onSuccess assign the response to the template var. Commented Dec 10, 2010 at 20:56
  • It will probably give solutions for server-side compiled scripts. Hogan.JS mentions something like this: twitter.github.com/hogan.js
    – Benny Code
    Commented Jan 30, 2013 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.