0

Hi i am new to this Mustache.js I have a template and js code as below

 var template = $('#pageTpl').html();
   var html = Mustache.to_html(template, data);
    $('#sampleArea').html(html);

and this is template code:

<script id="pageTpl" type="text/template">
    <div data-role='page' id='videodiv_{{device_id}}'>
        <div data-role=header>
            <h1> Device Page </h1>
        </div>
        <div data-role=content>
            <img id='vid_{{device_id}}' src='http://localhost//mjpg/{{device_id}}' width='320'>
        </div>
    </div>
</script>

this code works fine when i keep the template script in html page. but i want to keep template separately and use it. is there any way to do this?

ashok_p
  • 741
  • 3
  • 8
  • 17

1 Answers1

4
$(document).on('pageinit', function() {
    $.getJSON('assets/data/channels.json', {}, function(channelData, textStatus, jqXHr) {
        var channelList = $('#channels');

        $.get('assets/templates/channelList.mustache.html', function(template, textStatus, jqXhr) {
            channelList.append(Mustache.render($(template).filter('#channelTpl').html(), channelData))
            channelList.listview("refresh");
        });
    });
});

Source: http://www.levihackwith.com/how-to-load-mustache-js-templates-from-an-external-file-with-jquery/

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124
  • I'm tryng to use your solution to create a header from a template but when I'm trying to access the file, the security policy (Cross origin don't support html) prevent me to access it. How could I use this example (knowing that I can't use a server since it's also design to be use with an Android Webview (offline). Thanks – AxelH Apr 22 '15 at 10:14
  • Just be aware that the `$.get()` call is Asynchronous so returned results might not be in the order you would expect them. – artomason Mar 09 '19 at 15:15