Open Source 25 Mar , 2013
If the project is relatively simple, you can use Underscore.js. For the most part, this library offers functional programming utilities, but it does have a
_.template method that couldn’t make things easier. By default, it uses the ERB-esque
<%= %>delimiters, but that can easily be modified. The beauty of this solution is that any project that requires templates will likely have Underscore loaded already, simply due to its sheer general usefulness.
If you need something with a bit more zest, might I recommend Handlebars? With many useful block expressions (such as
#each for looping and
#if for conditionals) and the ability to register your own helper functions, Handlebars will give you everything you need to create even the most complex of templates.
There will be times, when the data that you are inserting into a template won’t quite be formatted in the way you prefer. In these situations, you’ll need to create custom functions to format it. If you’re using something like Handlebars, you can easily register a helper function; but other solutions, like Underscore, don’t offer that functionality. You’ll have to roll your own.
script tag with an alternate
typeattribute, so that the browser doesn’t attempt to execute them. It’s fairly easy to grab the
innerHTML attribute of the
scripttag and pass it to the template-creating function, when you’re ready.
However, this isn’t the only way to do it; in fact, it might not be the optimal way. There are several alternate solutions that might be better, especially in more complex scenarios.
This won’t always be applicable, but, in some cases, it can be really helpful to make your templates update automatically, when the data they are displaying changes. I like this idea a lot, because it allows even the UI of your application to be completely data-driven: when a model attribute updates, the UI updates with it. This is the basic principle behind tools, like Knockout.
While you could probably roll this functionality on your own without too much trouble, all the popular frameworks have it built in. For example, in Backbone, a template’s
initializefunction might include some custom event listeners…
If you aren’t careful, very quickly, your templates can get out of hand and become unwieldy. This is why it’s always a good idea to limit your templates to a reasonable size. If you make them too large, they’ll be more difficult to update, and won’t allow for a good separation of the code. On the other hand, if they’re too small, they’ll cost too much for what they bring, and will subsequently slow down your app.
You might want to get through