Using external templates with jQuery Templates
JavaScript, jQuery, UI By Dave Ward. Posted October 5, 2010Now that jQuery Templates is official and definitely will not include remote template loading, I wanted to publish a quick guide on implementing that yourself. As I mentioned previously, there’s a handy interaction between jQuery Templates’ API and jQuery’s AJAX methods that makes this easier than you might expect.
In this post, I’ll show you how to use a plain string as a template, how to asynchronously load an external template file as a string, and how to render it with jQuery Templates once it’s loaded.
Defining an external template
Defining a template suitable for remote loading requires almost no extra effort. Simply create a new file and fill it with the same sort of jQuery Templates fragment that you might normally embed in a text/html <script> element.
For example, given this person object:
var person = { name: 'Dave' };
You might define this template for that data in a file called PersonTemplate.htm:
<p>Hello, ${name}.</p>
Be sure not to wrap the template in a <script> element. Since we’ll be loading it remotely, that obscuring measure isn’t necessary. Also be sure not to include any of the HTML boilerplate that may come along with creating a new HTML file in your editor of choice, like <html> or <body>.
An added bonus that comes along with dropping the <script> container is that you get more reliable syntax highlighting for the template’s markup. Most editors don’t provide HTML syntax highlighting within <script> elements, even when their type is text/html, but work fine in the external files.
Using strings as templates
Though most jQuery Templates examples revolve around referencing template definitions hidden inside <script> elements, it’s also possible to provide the template as a plain string. Using the $.tmpl(template, data) syntax, a simple string version of the template may be provided as that first parameter.
For example, these are both perfectly valid ways to render a template, using the person object from the previous section:
// Specifying the template inline. $.tmpl('<p>Hello, ${name}.</p>', person); // Assign that same template to a JavaScript variable, and then // use that string value as a template parameter to $.tmpl(). var salutationTmpl = '<p>Hello, ${name}.</p>'; $.tmpl(salutationTmpl, person);
With that ability to use a string as a template, we just need a way to get the external template file’s content loaded into a string variable.
Loading the external template
With that in mind, probably the easiest way to load an external template is to use jQuery’s $.get() method. When you target $.get() at a static HTML file, the result passed to its callback is a string containing the file’s content. Exactly what we’re after.
For example, if an external template were stored in a file named PersonTemplate.htm, this is how you could use $.get() to load and render that external template with jQuery Templates:
// Asynchronously our PersonTemplate's content. $.get('PersonTemplate.htm', function(template) { // Use that stringified template with $.tmpl() and // inject the rendered result into the body. $.tmpl(template, person).appendTo('body'); });
That’s it.
Because you have to get involved with more of the moving parts, this is slightly more complex than jTemplates’ processTemplateURL, but it’s very manageable.
Caveats
Compilation caching – When you use this method, it’s important to keep in mind that jQuery Templates will not automatically cache the compiled template. If you intend to reuse the same template many times during a given pageview, this approach is slower than the embedded <script> technique.
It’s possible to work around that drawback by using $.template() to compile the remotely loaded template and store it manually, but I’m omitting that here to keep things simple.
If you’re interested, I’ll cover that in follow up post.
HTTP caching – In production, you should ensure that your server’s caching configuration is correct. If your server sends a proper expires header, requesting the same template multiple times during the lifespan of a page will only cause the browser to make one HTTP request. Even subsequent HTTP requests to check for a 304 status aren’t necessary if a future expires header is set on the response.
Template file naming – I recommend using a standard filename extension for your external template files, like .htm or .txt. I started out using more descriptive extensions like .tpl, but server configuration was a constant hassle. Important things like HTTP compression, expires headers, and even serving the files at all are common issues when using nonstandard extensions.
Similar posts
What do you think?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.
8 Mentions Elsewhere
- Tweets that mention Using external templates with jQuery Templates | Encosia -- Topsy.com
- A third option for using jQuery templates | Lazycoder
- links for 2010-10-08 — Business Developer Talk
- .NET Links of the Week #40
- .NET Links der Woche #40
- Solutions Log → Using External Files as jQuery Templates
- Using JavaScript templates for clean, dynamic HTML | Emma Tech
- Infuser – a Template Loader « If & Else



Great post, thanks! We’re looking forward to incorporating the new templating system into our frameworks..
“Most editors don’t provide HTML syntax highlighting within script elements…”
The best way around this I have found in Visual Studio is using inline asp.net tags:
This will render the script tags and allow you to write and edit html with highlighting (and intellisense).
You could do a pseudo file extension, and name external templates something like…
_template.tpl.html
Prefixed with an underscore to indicate it’s a partial (ala Rails), and with a .tpl.html “extension” to show that it’s a template JS template file (not an HTML partial to be rendered server-side).
Anyway, just a suggestion.
That’s a good idea. I like it.
Also, to “cache” the result of a template, I think it could be as easy as assigning the results to a variable…
http://gist.github.com/613688
Sorry for the double-posting. Just occurred to me, but not until after my first post. :)
With good expires headers, the result of the $.get() will be cached. So, at a string level, the caching isn’t a big issue. It’s definitely a measure slower to create an XHR object, but there won’t be an HTTP request.
During rendering, the templates are “compiled” to JavaScript functions and the result of that compilation can be cached. When you select a template in a script element, that compilation caching happens automatically. Using strings, there’s an extra step necessary to achieve that.
In any reasonably complex site there will be many templates, and storing each template in a separate file doesn’t seem very scalable/workable, surely it would be better to store them all in a single template file which can be retrieved once and thereafter the individual templates extracted and used as needed? Is there an existing pattern / best practice jQuery for doing this?
Especially on a large site with many templates, I wouldn’t want to store all my templates in one file. No sense in downloading a bunch of report templates just to render one search results template, for example.
I do like grouping composite template fragments that will be rendered together. An invoice template with several different line item templates is an example of that. It makes sense to store those together so you only need one HTTP request for templates to render the entire invoice.
I’ve been experimenting with two different ways to do that with jQuery Templates. I’m still not sure which I like best. I’m not quite ready to write about it until I’ve used it a bit more in production.
I agree, grouping templates by type/usage is the most desirable/pragmatic approach, I’ll look forward to seeing what you come up with…
Hi Dave, how are those grouped templates performing in production?
I’ve been happy with this approach thus far. The only sticking point I’ve run into is versioning the templates via filename or querystring, to avoid caching issues after updates.
I guess my $64,000 question is: Even though you can manipulate jQuery Templates to do remote template loading, would you choose to go that route or stick with jTemplates?
I’ll be using jQuery Templates for everything going forward. I’m not sure it’s quite as powerful as jTemplates, but it does handle everything I use jTemplates for. I believe it being included jQuery core in 1.5 and the amount of documentation/support already available make it a better choice.
A year from now, using any other templating plugin with jQuery 1.5 will probably be as obscure as using the LiveQuery plugin with jQuery 1.4 today.
Excuse me for the off-topic-comment, but still… The SEO aspects of jQuery Templates doesn’t seem to be all that great? Rendering it useless for highly-SEO-dependent content right? Of course, one could mix it up with server side rendered asp.net or something… seems redundant in a way?
Please correct me if I’m out of my element ;).
Regards/Jesper Wilfing
That’s right. If it’s rendered with JavaScript, assume it’s invisible to search engines. That is, unless you use the #! convention to provide Google with a server-generated version of the same content, ala: http://code.google.com/web/ajaxcrawling/docs/specification.html
RequireJS is a nice tool when it comes to loading these remote templates. You can use its ability to specify a text file dependency when defining a module. The added benefit is that if you use Require’s optimization tool, I believe it will intern the template into your JS, eliminating the extra HTTP request for the template in production while allowing you to maintain the template file separately in development.
Your article is very informative, but some doubts arose: I need the template ID to interact with other libs, like KnockoutJS
Also, what’s your approach with bigger apps that need some kind of advanced routing mechanism?
I’m not a big fan of the single page interface pattern unless there’s a very good reason for it, like sites with a chat feature that should persist through page state changes. So, I don’t spend much time thinking about routing on the client-side. I’ve heard good things about Sammy and Backbone though.
Hey…
I was reading through some posts here, where you write asp net ajax is dead, etc. now here, jquery templates.
One question: Do you know something about Asp Net Ajax Templates and Binding? Well, because everybody is praising jquery and so on, I have never seen ever such possibilities and easy implementation on realy complex things, that msajax templates and binding can do.
I think, even if ajax control toolkit is out, and maybe jquery is better than ms ajax, the asp net ajax templates and binding are absolutly great tools, that make so many things easier for me, for which i have to invest much more effort in jquery or other libaries.
jquery alone is to less for me, so is msajax. But the combination is realy great.
What do you think?
Have you tried KnockoutJS? It solves the binding problem, saves a lot of lines of code manually adding or hiding stuff
The Ajax Library’s DataView showed a lot of potential (I’m definitely familiar with it; I wrote about 15,000 words about it for a book chapter), but it was abandoned before it was fully completed.
If you already have jQuery on your page, you’re getting jQuery Templates for free in 1.5, so it doesn’t make sense to pull in a redundant templating library at that point. To get the same sort of two-way binding that the DataView offered, take a look at the jQuery Data Link plugin. It’s very similar (which isn’t surprising, since Dave Reed at Microsoft worked on both).
ya… i looked into it. It does something, what ms ajax template and binding does too… I dont see any reason, why knockout should be prefered, maybe because it has a nice website?
Maybe because it ‘s clean javascript, without any other dependencies and a good learning curve? :)
@Alisson hm, as i can read it is dependant to jquery and jquery template… I was not talking about binding alone…
i looked into the data link plugin too, @Dave, I´m sure you know, that with the DataView and Binding you can do the same with much less coding.
“but it was abandoned before it was fully completed.” BUT WHY?????
KnockoutJS has no dependencies, only if you want the template stuff, which is optional.
C’mon, this DataView stuff is restricted to ASP.Net, javascript is the lingua franca of the web.
nice
Alisson I am a asp.net programmer… Keep in mind this blogs title… Therere many points I like in msajax that are nowhere else. Did you know that you can integrate jquery into asp.net and combine this way two great js libraries? Like me, I came to jquery quite late. You know what? I am able to put all my library Ive written, all my classes, all my client controls and extenders into jquery… I just need two references, msajax and jquery, ms ajax merges them together. And there are still situations where i still write my plugins as classes and controls or extenders, there are many greate options compared to just plugins. I like the msajax ComponentModel.
This article really convinced me to start using this as a standard practice.
Now that jQuery, as of v1.5, has deferred objects, there are some great possibilities for loading external templates in a more efficient manner.
I created a jQuery plugin called tmpload that streamlines the use of external templates, pre-compilation, caching and deferred objects. If you’re interested in external jQuery templates, you should definitely check it out.
markdalgleish.com/projects/tmpload/
http://github.com/markdalgleish/tmpload
Hi Dave
Checking out external templates, I created a messy output. What did I do wrong?
I modified the “movies” example from http://api.jquery.com/jquery.tmpl/
Thanks
File: movie.tmpl.htm
File: movies.htm
And this is literally its output…
You’re close. You just need to pare down the external template to markup only:
movie.tpl.htm:
Thanks
That works for me!
One difficulty we’re currently facing, that may rear its ugly head using this approach:
If you cause your browser to make a GET request, like via jQuery’s $.get() function, and you hit an asset that exists in your application cache, the HTML5 specification does not specify that the response have its HTTP response code set to 2xx indicating a success.
In our testing, Chrome will attach a success header, Mobile Safari on iOS will not. This means that if you’re hitting a template file that’s in your application cache, jQuery will think your $.get() failed, rather than succeeded!
You can get around this by specifying the isLocal flag on that request, using
That’s very interesting, has anyone reported/raised it with the W3C and/or WhatWG so that they can address it in the HTML5 specs?
I found this works to include templates in external files:
<!--#include virtual="Scripts/RenderTemplates.js" -->That would work pretty well for including templates you know you’ll need immediately and need on every pageview. The AJAX-based loading approach I’m showing here is useful when you don’t need to render the template immediately or might not even render it at all on some pageviews. In those cases, deferring the template load helps speed up the initial pageview by not burdening it with unnecessary markup.