If you read the earlier Quick Tour and Views and Events chapters, you already have a measure of experience with Eco (Embedded CoffeeScript) templates. This chapter will focus on Eco, beginning with basic usage in order that you understand Eco's moving parts, then progressing to more complex patterns and the use of third-party helper functions. Backbone components will make an appearance in many of the examples, in order to provide practical guidance for application development.

Templates are used in almost every Backbone application, but they are not officially part of Backbone. Backbone has no dependency whatsoever on templates, and I do not know yet of a general templating library that has a dependency on Backbone. In my own work, I have had several opportunities to use Eco without Backbone. Introducing templates into a legacy JavaScript application can be a great first step when refactoring to a more structured approach that may eventually also include Backbone. Templates are also useful for generating output other than HTML, such as dynamically generated source code. When you run an example in this book, the editor.log, editor.out.html, and editor.out.append functions are in fact generated on the fly from Eco templates containing CoffeeScript.

Why Eco?

This book chooses Eco for rendering dynamic HTML for the following reasons. To remain manageable, templates must keep their interpolated programming code from growing too verbose, lest the readability of the template suffer too greatly. This is not a problem when the dynamic elements are simple properties, but in almost every application, logic (and therefore, arbitrary programming code) is required for most templates. The so-called logic-less approach to templating, promoted by Handlebars and other Mustache implementations, employs special syntax and custom helpers to move the arbitrary code out of the templates, but this indirection can grow cumbersome. Eco leverages all of CoffeeScript's clean, readable power for a solution that gets the job done with a minimum of fuss.


The rest of this chapter is part of the interactive book Backbone + CoffeeScript.