The jQote2 API Reference provides plenty of useful examples which are sure to help users get up and running quickly. I found it a bit unclear, though, as to how templates could be loaded externally as, in the reference examples, templates are defined within the containing page. For the sake of simplicity this approach certainly makes sense in the context of examples. However, in practice, templates would ideally be loaded externally.
While jQote2 provides a perfect API for templating, it does not provide a method specifically for loading external templates; this is likely due to the fact that loading external templates could easily be accomplished natively in jQuery. However, since this is a rather common development use case, having such a facility available would be quite useful.
After reviewing the comments I came across a nice example from aefxx (the author of jQote2) which demonstrated a typical approach to loading external templates which was simular to what I had been implementing myself.
And so, I wrote a simple jQuery Plug-in which provides a tested, reusable solution for loading external templates. After having leveraged the Plugin on quite a few different projects, I decided to open source it as others may find it useful as well.
Using the Plugin
Using the jQote2 Template Loader plugin is rather straight forward. Simply include jQuery, jQote2 and the jquery.jqote2.loader-min.js script on your page.
As a basic example, assume a file named example.tpl
exists, which contains the following template definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <script type="text/html" id="articles_tpl"> <![CDATA[ <% var article, i, n; for ( i = 0, n = this.articles.length; i < n; i++ ) { article = this.articles[i]; %> <article> <header> <h1><%= article.name %></h1> </header> <p><%= article.text %></p> </article> <% } %> ]]> </script> |
We can load the example.tpl
template file described above via $.jqoteload
as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $.jqoteload('example.tpl', function(templates) { // create some mock articles... var articles = [{ name: 'Article A', text: 'Articles A test...' }, { name: 'Article B', text: 'Articles B test...' }, { name: 'Article C', text: 'Articles C test...' }]; // Render the articles... $('#articles').jqoteapp(templates.articles_tpl, { 'articles': articles }); }); |
After example.tpl
has been loaded, from another context we can access the compiled templates via their template element id
. In this example "articles_tpl"
.
1 2 3 4 5 | //... within some other context, access the same // compiled template var template = $.jqoteret( 'articles_tpl' ); |
You can grab the source and view the example over on the jQote2 Template Loader Github page.
Hi Eric.
It was about time that someone threw together a decent solution to that external template mess. Thank you very much for it.
Regards,
aefxx
No problem. Thanks for jQote2.
Best,
Eric
Very helpful, and thanks.