Skip to content

Instantly share code, notes, and snippets.

@trey
Created May 18, 2012 03:08
Show Gist options
  • Select an option

  • Save trey/2722910 to your computer and use it in GitHub Desktop.

Select an option

Save trey/2722910 to your computer and use it in GitHub Desktop.
Using External Files as jQuery Templates

Using External Files as jQuery Templates

Previously…

If you want to keep your templates in external files, you can load the template in like so:

$.get('/js/templates/filename.html', function(template) {
	$.tmpl(template, data).appendTo('#whatever');
});

A couple of benefits of this method:

  • Organizing your templates into their own files is tidy.
  • Your syntax highlighter will be happier, since you're not writing HTML between two <script> tags.

Source

@trey

trey commented May 18, 2012

Copy link
Copy Markdown
Author

@postpostmodern

Copy link
Copy Markdown

I used to do this, but executing your code as a callback gets pretty hairy when you need to load several inter-dependent templates. You end up with a bunch of nested callbacks.

I think it's best to compile js templates into pure Javascript and load them with <script> tags.

@Synryu

Synryu commented Apr 5, 2013

Copy link
Copy Markdown

A little question, is it possible to use nested template with external files ?
Something like that :
...
{{if condition}}
{{tmpl(subData) $.get("myFile.htm", function(template){$.tmpl(...);})}}
{{/if}}
...

@JoshMock

JoshMock commented Nov 5, 2013

Copy link
Copy Markdown

If you're using Require.js it has a super handy text! prefix that loads any file into a variable as a string. That's what I do. There are probably standalone libraries that accomplish the same thing without using $.get, but your way works in a pinch, albeit with a little inline async/callback behavior that could get annoying.

Side note: $.tmpl is deprecated so you may want to consider a different template engine. Might I suggest the one built into Underscore?

@trey

trey commented Nov 6, 2013

Copy link
Copy Markdown
Author

@JoshMock Thanks for the info on text!. Some day I'm gonna pick your brain about how you use Require.js.

And, yes, I realize this entire example is way out of date and I wouldn't use $.tmpl anymore. Just remembered I had this Gist sitting around from a while back and thought it served the example well enough. :)

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