Description #
Underscore Templates are a lightweight JavaScript templating system built into the Underscore.js library. They use a simple embedded syntax for rendering dynamic content in HTML.
History #
Underscore.js was created by Jeremy Ashkenas in 2009 as a utility library for JavaScript. Its built-in templating engine was one of the earliest client-side solutions for rendering HTML with data, inspiring many later systems like Lodash templates and even Backbone views.
Hello World Code #
<script type="text/template" id="hello-template">
<h1><%= message %></h1>
</script>
<script>
var template = _.template(document.getElementById('hello-template').innerHTML);
var html = template({ message: "Hello, World!" });
document.body.innerHTML += html;
</script>
How to Run #
Option 1: Online
Try it in JSFiddle or CodePen with Underscore.js loaded:
https://jsfiddle.net/
Option 2: Local
Include Underscore via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
Then create a <script type="text/template">
and render using _.template()
.
Key Concepts #
- Uses
<%= %>
for escaping,<%- %>
for unescaped output - Interpolation of data via JS objects
- Supports logic: loops, conditionals with
<% %>
- Pure client-side templating
- Extremely lightweight (~4KB for template engine)
- Works with Backbone.js views
- HTML-based with embedded expressions
- Minimal dependencies — just JavaScript
- Fast enough for small-to-medium apps
- Precursor to more advanced JS templating systems
Try It Online #
https://jsfiddle.net/ (load underscore.js to try templates)
Fun Facts #
- Part of the original Underscore.js utility suite alongside functions like
map
,reduce
, andfilter
. - One of the earliest and simplest JavaScript templating tools.
- Underscore templates still power many legacy projects and internal admin tools.
Resources #
Official site
Docs or tutorial
GitHub or interpreter
Community or learning resources