Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Mustache HTML template from external <script />

I'm using Mustache.js to render different recurring parts of an HTML site. Until now I have every template inside a <script /> and access its contents through jQuerys html() method:

<script type="text/html" id="html-script">
    <!-- ... -->
</script>

<script type="text/javascript">
$('script[type="text/html"]').each(function() {
    var $this = $(this);
    templates[$this.attr('title')] = $this.html();
});
</script>

Now I would like to put each template in its own file and include them like this:

<script type="text/html" id="html-script" src="template.html"></script>

This does not work so my question is

  1. Why not?
  2. How can get this to work?

I read an article about How to Load Mustache.js Templates From an External File with jQuery which I could use as a fallback solution but I would really appreciate if I not had to $.get() the templates myself.

like image 886
hielsnoppe Avatar asked Feb 26 '26 02:02

hielsnoppe


1 Answers

While the w3c spec is confusingly vague on what the srcof a <script> element can be, it does say that "A resource is a script resource of a given type if that type identifies a scripting language and the resource conforms with the requirements of that language's specification." Practically, this means that a browser will only load javascript, and you cannot interact with an HTML document loaded this way.

I would rethink the way you are trying to solve your problem. This is a solution to asynchronously load template files stolen from the ever helpful Christophe Conraets:

// Asynchronously load templates located in separate .html files
function loadTemplate (views, callback) {
    var deferreds = [];

    $.each(views, function(index, view) {
        if (window[view]) {
            deferreds.push($.get('tpl/' + view + '.html', function(data) {
                window[view].prototype.template = _.template(data);
            }));
        } else {
            alert(view + " not found");
        }
    });

    $.when.apply(null, deferreds).done(callback);
}

loadTemplate(['view', 'view2','view3'], function() {
    // do amazing things...
});

[source] (obviously, modify the tpl directory to suit your needs)

You could also do this with something like require.js (my preffered method).

like image 87
Nick Tomlin Avatar answered Mar 05 '26 10:03

Nick Tomlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!