O'Reilly logo

JavaScript Programming: Pushing the Limits by Jon Raasch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4

Using JavaScript Templates

Templates are the best way to generate long strings of markup in JavaScript. Instead of creating markup piece by piece by appending individual elements to the DOM, you build a template that generates an entire chunk of markup at once. Templates eliminate the need to mix markup into your JavaScript, and make generating DOM content much more intuitive, because they provide a dedicated place for markup, which will compile according to the variables you pass into it. That means your JavaScript can still drive the content of the template, without having to mix with it.

In this chapter, you learn why you should be using templates and about some different libraries you can use for templating. Then you discover the basics of using Underscore templates: how to mix markup strings with variables, and how to include basic bits of JavaScript such as loops. You also find some best practices on how and where to include your templates. Finally, I'll tie in what you learned in Chapter 3 and teach you how to incorporate templates into Backbone using them to render views.

Introduction to Templates

JavaScript templates will revolutionize the way you inject markup into the DOM. They make it easy to generate long strings of markup that are driven by JavaScript variables, yet remain separate from the domain logic of your application.

Why Use Templates?

When it comes to code organization, JavaScript templates are one of the most important techniques you can use. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required