Can I load partials from another file in Mustache.js?

1.9k views Asked by At

I'm trying to load in partials from a separate file while using mustache.js but it's proven difficult. The PHP implementation makes this very easy, but not so much in the JS side.

I've gone through the docs and can't find anything related to this, only using an object as a partial instead of a file.

Here's some sort of psuedocode to explain what I'm trying to do.

$.Mustache.load('/mustaches.php', function () {

    var item = { thing: 'one' };
    var partial = 'partials/actions.mustache';

    $('.container').mustache(
        'main_mustache',
        {item: item},
        partial
    );

});

So, I'd like to be able to load a secondary file as a partial an include it with the template to be used so I don't have to duplicate code across all the different templates I use.

With something like Blaze I can import a template with {{> templateName}} but it doesn't seem to be quite so easy with Mustache.js.

If this isn't possible with Mustache, what other libraries would you recommend?

1

There are 1 answers

1
taxicala On

You could load both templates with mustache, and then pass one of them (the partial) to the one that should render the partial. Be aware that in order to make it work, in the mustache where you want to render the partial, the variable name should be enclosed in triple curly bracers in order to tell mustache that it should be html:

<div>
    <h1>This is my title</h1>
    {{{partial}}}
</div>

and then:

$('.container').mustache(
    'main_mustache',
    {item: item, partial: partial},
);