Storing jquery / js templates in separate files

I am trying to figure out how to store jQuery templates in different files from the base html (without using a string or ajax request).

For example, in my html page, I would like to do this:

<script type ="text/x-jquery-tmpl" id="personTmpl" src="js/personApp.tmpl.html"></script> <div id="container"></div> <script type="text/javascript"> var p = { name: 'joe' }; $( "#personTmpl" ).tmpl( p ).appendTo( "#container" ); </script> 

If #personTmpl is defined in personApp.tmpl.html (or somewhere else)

The ultimate goal is to just keep my template separate from js code (and html).

I don't like the string method because it makes editing tough for longer templates. And I don’t want to run an ajax request to load (note that the template file will eventually be aggregated for production).

Thoughts?

+4
source share
3 answers

I had a similar situation, and my solution was to write a template caching object that was responsible for loading the template using ajax the first time it was requested and stored in memory from now on. It worked pretty well for my project. I can post the code that I used if you are interested.

0
source

I solved this problem using requirejs along with my text plugin. During development, templates are loaded using an XHR request. During deployment, I optimized the use of the requirejs r.js file, and then the templates were included in the main js file, preserving the number of downloaded files.

0
source

There is currently an API development ( HTML Imports ) to do this - an overview in HTML5Rocks . However, since this is under development, this is probably not suitable, with the exception of applications that may live with limited browser support.

Another option is to come up with your own using Ajax and / or your build system.

0
source

All Articles