Replacing Rails Components | 283
Logical separation
The inability to execute code in the views forces model- and controller-related
code into the models and the controllers. This helps encourage good boundaries
and separation of concerns appropriate for a web application.
Security
Because the Ruby environment is protected against dangerous or malicious code
in the templates, you can use Liquid to give customers or users access to tem-
plates without security concerns.
To get started with Liquid and Rails, install the Liquid plugin fromhttp://liquid-
markup.googlecode.com/svn/trunk. The plugin registers a template handler for all
view files with an extension of.liquid. You can mix and match your Liquid views
with standard Rails views, and the Liquid views get all of the assigned instance vari-
ables from the controller. The following is an example of Liquid code:
<h1>Users</h1>
<ul>
{% for user in users %}
<li>{{ user.name }} ({{ 'edit' | link_to: user.edit_url }})</li>
{% endfor %}
</ul>
Haml
Haml is a very terse markup language designed to concisely represent HTML. Haml
was created by Hampton Catlin and is available fromhttp://haml.hamptoncatlin.com/.
The Haml philosophy is summarized on the tutorial page: “Every character means
something.” We see this in several ways in Haml:
- There are no closing tags; indentation denotes nesting.
- The verboseidandclassattributes are shortened to their CSS equivalents#and.,
respectively. - The commonly useddiv tag can be omitted altogether.
- Rails HTML output is expressed by a single= sign instead of ERb’s<%= %> tags.
Haml’s terseness can make it a bit difficult to understand at first, but many people
find it useful and less intrusive than ERb markup. Our example can be coded in
Haml as follows:
%h1 Users
%ul
- @users.each do |user|
%li
= user.name
= link_to('edit', user.edit_url)