Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

282 | Chapter 9: Incorporating and Extending Rails


Alternative Template Engines


The standard Rails template engine uses Ruby’s ERb (embedded Ruby), which is a
very powerful template system. However, it may be too powerful for some applica-
tions. The PHP-like free embedding of code within views can encourage placing too
much logic in a view, which the MVC architecture frowns upon. Writing HTML
code through ERb can be a painful process, as the developer must switch back and
forth between thinking in HTML and thinking in Ruby.


There are some other options on the continua of power and uniformity, and Rails
has a flexible extension system that allows different handlers to be simply registered
for different view file types. We will look at three markup languages, available as
Rails plugins: Markaby, Liquid, and Haml.


Markaby


Markaby (http://redhanded.hobix.com/inspect/markabyForRails.html) is a markup
language for HTML, bywhy the lucky stiff(Rails plugin due to Tim Fletcher). Its
advantage is that it is pure Ruby. All tags have a corresponding Ruby method, simi-
lar to Ruby’s Builder library. The markup looks like this:


h1 'Users'

ul do
@users.each do |user|
li do
user.name
link_to 'edit', user.edit_url
end
end
end

Markaby can be installed as a Rails plugin fromhttp://code.whytheluckystiff.net/svn/
markaby/trunk. Once installed, you can create templates that use Markaby by giving
them a.mab extension.


Liquid


Liquid (http://www.liquidmarkup.org/), by Tobias Lütke, is another alternative Rails
template engine. Its main advantage is that it is secure. It does notevalany of its
input; it only substitutes provided values into a template with some optional filters.
This division of labor has several advantages:


Simplicity
There are only a few basic constructs in Liquid: the simple ones are literal
HTML code, variable interpolation, filters, conditionals, and loops. This makes
the templates clean and easy to understand, which is an advantage when the
designer is not a developer.

Free download pdf