Skip to main content

doT templates for JavaScript

June 10, 2014 mgroves 0 Comments
Tags: JavaScript doT jQuery

A project I'm working on now has a SPA project that uses the doT template engine.

Using it isn't terribly different from other JS templating engines (like Mustache), so if you have experience with those, it should look pretty similar.

First, you need a template. Just define it in a <script></script> block like so:

Notice the {{ }} areas in the template? That's what doT is going to fill in with whatever data we want (i.e. interpolation). The data that will be passed in is simply a JavaScript object, and this template knows that object by the name "it". So you can think of "it" as kinda like a keyword.

The next step would be to get the data, get the template, and combine them together to get an output.

Note that I'm using jQuery for convenience, but it's not required.

doT demo in Chrome

doT also offers conditionals and looping. It claims to be the "fastest + concise" templating engine for Node.js and browsers. If performance is a major concern for your templating engine, you can check out their benchmarks. Seems to be a close race depending on the browser, but doT is no slouch. Personally, I believe that templating is (hopefully) such a small part of the overall performance of a typical SPA app that it won't keep me up at night.

Comments

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter