Created
July 11, 2012 04:24
-
-
Save anonymous/3087987 to your computer and use it in GitHub Desktop.
External Template Loader for Kendo UI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
This was nice to begin with, but is not practical for situations where you have separated your template ("Views") into several files.
Also, it uses a deprecated jQuery calls which are to be removed at some point...
I've re-written a function to address this issues at https://gist.github.com/amirgalor/8705653
it accepts a "JSON" array of {path: "path to file", tag: "script's tag to attach to dom"}