Search code examples
jqueryajaxtemplatesexternalmustache

How to apply jquery mustache to external file/template


I am using this to 'get' my external html file, and then use mustache to append to that template's id:

 $.get('block.html', function(data) {
        $('#mydiv').append(data);
        
            var list = {
                       name : 'whatever'  
            };
                        
            $('#Block').mustache(list).appendTo('#mydiv');
    });

The file block.html would look like:

<script id="Block" type="x-tmpl-mustache">
My name is {{name}}
</script>

Is there a better way of doing this? Because, at the moment, I am appending twice.


Solution

  • Well, the jquery mustache plugin is great for when the template is inside your current document.

    But here you have a different use case and the helpers provided by mustache itself are sufficient to do the job. So, just :

    $.get('block.html', function(template) {
        var view = {name:'whatever'};
        var html = Mustache.to_html(template, view);
        // and now append the html anywhere you like
    });
    

    And in this case, your block.html can become:

    My name is {{name}}