Cover by Brian Carper, Christophe Grand, Chas Emerick

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

O'Reilly logo

Templating

Thus far, we have done just about everything a web framework can be expected to do, with the notable exception of actually producing complex HTML. While HTTP services and file servers are useful, most people think “HTML” when they hear “web application.” Most web frameworks use template systems where HTML is intermingled with executable code or unevaluated “directives” that refer to bound variables defined for the scope of page generation, resulting in a populated page of HTML.

A sample of this approach is Ruby’s ERB templating language:

Example 16-4. Example of an ERB HTML template

<h1>Hello, <%= @user.name %></h1>

<p>These are your friends:</p>
<ul>
<% @user.friends.each do |friend| %>
  <li><%= friend.name %></li>
<% end %>
</ul>

Those unfamiliar with ERB syntax may be puzzled, but this is not so dissimilar to Django templates or JSPs or any of a hundred other templating systems you might be familiar with. All of these systems work primarily by string substitution; in ERB’s case, executing Ruby code found within <% and %> delimiters, and evaluating expressions within <%= and %> delimiters to obtain strings that should be included in the output. ERB templates run inside a context, so expressions like @user.name refer to a local inside the context, obtaining its name attribute.

This approach has been used by numerous languages and millions of programmers for years; this is even the primary mode of operation in the case of PHP. However, not all is well. The first obvious problem ...

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