Loading mustache template in jQuery returns Document object instead of raw string

1.7k views Asked by At

I am using icanhaz.js and mustache for loading templates, and I am loading mustache templates on demand using the following method:

loadTemplate: function(name, callback) {
            if (!ich.templates[name+"_template"]) {
                jQuery.get("/js/templates/"+name+".mustache", function(data) {
                  window.ich.addTemplate(name+"_template", data);
                  callback();
                });
             } else {
                callback();
             }
        }

Inspecting the data variable that gets returned in the debugger, however, it sometimes comes back as a Document object rather than a raw string that I can use. I say sometimes because the template loads as desired if the html in the template file has no nested DOM element at the top of the file. This is very strange behavior that I would love some help explaining.

So, for example, the template file:

<div>
     <div>My name is {{name}}</div>
</div>

would get returned as a Document object when loaded.

Whereas, this template file:

 <div></div>
 <div>
     <div>My name is {{name}}</div>
 </div>

is returned as needed as a raw string.

I'm not sure why having that top div without any children should make a difference as to the template being identified as Document vs. a string. Any ideas?

1

There are 1 answers

0
Frédéric Hamidi On BEST ANSWER

Since you're not providing a dataType argument to $.get(), you're running in "intelligent guess" mode. The related documentation says:

If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

So, your server might be sending some of the templates as text/html (or text/plain) and others as text/xml. It would be interesting to examine the response headers (using Fiddler or an equivalent tool) to check if that's actually the case.

As an aside, specifying the request's data type should get rid of the issue altogether:

jQuery.get("/js/templates/" + name + ".mustache", function(data) {
    window.ich.addTemplate(name + "_template", data);
    callback();
}, "html");      // Always return HTML as plain text.