#127: Basics of JavaScript Templating

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

A template is a chunk of HTML that you need to inject onto the page. Often templates are created “server side” – in that they come to the JavaScript fully formed and just need to be put into the DOM. But sometimes that isn’t feasible or would require and extra round trip to the server which might be slow. In that case having the template right in JavaScript is ideal. You can certainly just do a bit of string concatenation adding together bits of HTML and data until you have the template you need. But that likely isn’t ideal as it doesn’t separate the concerns of data and template. Real JavaScript templating can help here.

In this screencast we’ll cover the basic “why” of JavaScript templating and then specifically cover a simple example of how it’s done in Underscore.js. Then we’ll cover some other alternatives.

Demo

var compiled = _.template(
  "<div class='movie'>" + 
    "<h2><%= movie_title %></h2>" + 
    "<p><%= movie_desc %></p>" + 
  "</div>"
);

var i, toAppendString = "";

for (i = 0; i < data.movies.length; i++) {
  toAppendString += compiled(data.movies[i]);
}  

$("body").append(toAppendString);

See the Pen %= penName %> by Chris Coyier (@chriscoyier) on CodePen

Links