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

I use icanhaz.js and a mustache to download templates, and I download 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(); } } 

By checking the data variable that is returned in the debugger, however, it is sometimes returned as a Document object, not a raw string that I can use. I sometimes say because the template loads as desired if the html in the template file does not have a nested DOM element at the top of the file. This is a very strange behavior that I would really like to explain.

So, for example, the template file:

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

will be returned as a Document object upon loading.

While this template file:

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

returned as raw string.

I am not sure why having this top div without any children should matter in that the template is identified as a Document in relation to the line. Any ideas?

+4
source share
1 answer

Since you do not provide the dataType argument for $.get() , you are in “smart guess” mode. Related documentation says:

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

Thus, your server can send some of the templates as text/html (or text/plain ), and others as text/xml . It would be interesting to study the response headers (using Fiddler or an equivalent tool) to check if this is really the case.

Aside, setting the request data type should completely get rid of the problem:

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

Source: https://habr.com/ru/post/1379841/


All Articles