简体   繁体   中英

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

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?

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},
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM