1

I am using the koExternalTemplateEngine to load external templates.

This works fine when the template is located in the same site or served from another site on the same server.

However when I try to reference a template on a remote server it doesn't work. I get http 200 ok but with a status code of 0 (there is nothing in the Response and no html).

A code example is below:

<script src="Content/Scripts/ko/lib/koExternalTemplateEngine_all.js"></script> 
<script>infuser.defaults.templateSuffix = ".tmpl.html";
infuser.defaults.templateUrl = "http://www.anotherServer.com/koTemplates";</script>
<div data-bind="template: { name: 'koTemplate1' }"></div>

Is it possible to reference a template on a remote server and if so what am I missing?

nemesv
  • 138,284
  • 16
  • 416
  • 359
Simon Barnett
  • 69
  • 2
  • 9
  • This is a restriction in `$.ajax`/browsers that you cannot send requests to different servers from javascript: see http://stackoverflow.com/questions/1201429/jquery-ajax-fails-when-url-is-from-different-server – nemesv May 01 '13 at 07:53

1 Answers1

0

I suggest that you go down the route of using requireJS and its text plugin for loading external cross origin content and configure the xhr use there:

config: {
        text: {
            useXhr: function (url, protocol, hostname, port) {
                return true;
            }
        }
    }

you can use this property in requirejs config to set it to use xhr and activate CORS.

Make sure that this doesnt work in ie 6 and 7 and for ie 8 and 9 you need to use:

window.XDomainRequest

Once you did all this you can simlpy call your external template as a requirejs module dependency like this:

define("moduleName", ["ko", "text!templates/surveys.html"], 
function(html){
    $('body').append(html);
    ko.applyBindings(new viewmodel)...
});

Some good links for you: require.js is requesting html files but serving them as script elements

https://github.com/requirejs/text

Configuring xdr for IE

Community
  • 1
  • 1
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
  • It looks like I'm going to be hosting the template on the same server now so problem solved. I'll keep this in mind for the future though, thanks. – Simon Barnett May 01 '13 at 13:47