O'Reilly logo

Closure: The Definitive Guide by Michael Bolin

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 11. Closure Templates

In a web application, it is extremely common to dynamically build up a string of HTML and then insert it into the page. Most web frameworks provide a server-side template language, such as PHP or JSP, to address this issue. By comparison, Closure Templates (also known as “Soy”) provides a templating solution that can be used on both the server and the client from either JavaScript or Java. Soy generates JavaScript code from a template at build time, so it avoids the runtime parsing cost encountered by most JavaScript template systems. Further, because the code it generates for each template is a JavaScript function, it can be called or passed around as a functor in a way that is natural for JavaScript programmers. This chapter will explore the many features and benefits of using Soy.

Limitations of Existing Template Systems

Before diving into why Soy works the way it does, it is important to consider the problems that Soy is trying to address in other template systems that are available today.

Server-Side Templates

When using a template system that only works on the server, such as JSP or PHP, a template often resembles an entire HTML file with placeholders for variable text. In this way, the user of the template can insert values for the template variables at runtime to dynamically create a string of HTML that can be sent down to the client. The following is an example of a PHP file with a placeholder to insert the current year:

<html> <body> <h3>The year ...

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