Skip to content

Instantly share code, notes, and snippets.

Created July 11, 2012 04:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save anonymous/3087987 to your computer and use it in GitHub Desktop.
Save anonymous/3087987 to your computer and use it in GitHub Desktop.
External Template Loader for Kendo UI
var templateLoader = (function($,host){
//Loads external templates from path and injects in to page DOM
return{
loadExtTemplate: function(path){
var tmplLoader = $.get(path)
.success(function(result){
//Add templates to DOM
$("body").append(result);
})
.error(function(result){
alert("Error Loading Templates -- TODO: Better Error Handling");
})
tmplLoader.complete(function(){
$(host).trigger("TEMPLATE_LOADED", [path]);
});
}
};
})(jQuery, document);
@gabsoftware
Copy link

gabsoftware commented Apr 3, 2019

Thanks @amirgalor,

I also improved your version:

  • use TypeScript
  • taking advantage of the fetch API
  • taking advantage of the ...rest parameter syntax
  • added some usage examples
  • it's now a class instead of a function
  • removed jQuery dependency
  • returns a promise instead of triggering an event

Gist: https://gist.github.com/gabsoftware/616dca27dccdd4e3fb4c0480cb1b0b88

Usage:

import { TemplateLoader } from "path/to/TemplateLoader.js";

// first way
var p = TemplateLoader.loadTemplates(
    { path: "/templates/first.tmpl.htm" , tag: "first-template"  },
    { path: "/templates/second.tmpl.htm", tag: "second-template" }
);

// or second way
var tmplArr = [ { path: "/templates/first.tmpl.htm" , tag: "first-template"  },
                { path: "/templates/second.tmpl.htm", tag: "second-template" } ];
var p = TemplateLoader.loadTemplates( ...tmplArr );

// then use the promise
p.then(
    templates => {
        console.log( 'Templates loaded', templates );
        
        var firstTemplate = kendo.template( $( "#first-template" ).html(), { useWithBlock: false } );
        var result = firstTemplate();
        $( "#firstcontainer" ).html( result );

        var secondTemplate = kendo.template( $( "#second-template" ).html(), { useWithBlock: false } );
        var result2 = secondTemplate();
        $( "#second" ).html( result2 );
    }
);

@dtrimarchi : no need for events with my implementation, you can use the returned promise as you wish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment