Basic Template Engine

Sometimes I need to setup Javascript templating for a page or two, or even just a form. I found a cool solution over on Krasimir Tsonev’s blog. I thought I would save it here for future use.

Template

I don’t really like having to setup long strings in javascript, it is just so ugly. So I use the <script type=”text/template”> approach to separate out my templates from my code. Here is an example.

This is just a basic “Attendee” template for some event. Notice the <%stuff%> inside there. That is where the magic happens.

Template Engine

Here is where the real magic happens.

So as you can see the “TemplateEngine” just takes some input and replaces anything between the <% %> symbols. Krasimir actually has a more functional version setup on his blog as well with support for some logic, but that is more than I needed. And if I ever did need that much functionality I would just turn to a full Template Engine.

Update:

I noticed a strange flaw in this template engine when working with templates that require multiple replacements on the same line of text. Here is another version of the template engine you can use which should find all variables in your template, regardless of how many are on a line.