The McDev Blog

Kevin McKelvin's perspective of the Ruby world.

Slim Templates

The Slim template engine seems to have gained a lot of popularity in the Rails community recently. Their site describes it as ‘A lightweight templating engine.’ For a long time I’ve loved Haml, taking the approach that I’d rather describe my intent than hard code HTML tags all over the place.

However, in hindsight having used Slim for a while it appears Haml might have stepped a bit too far away from HTML, including some cryptic syntax like ‘%’ signs to declare tags.  Slim takes a step back towards HTML.  It still uses the significant whitespace element of Haml and removes the annoying <>’s, but keeps you closer to the actual HTML that you’re describing.

Here’s an example of Slim (taken from a presentation I gave recently)

1
2
3
4
5
6
7
8
p = link_to "New Link", new_link_path
- @links.each do |link|
  div class="link"
    div class="title" = link_to link.title, link.url, :target => "_blank"
    div class="description" = link.description
    div class="manage"
      = link_to "Delete", link, :method => :delete, :confirm => 'Are you sure?'
= paginate @links

Nice and clean. The way it should be :)

To install it in your Rails app, just add it to your Gemfile:

1
gem 'slim-rails'

Then create a view using the .slim file extension to start using Slim.

Resources to check out:

For those using vim and the rails.vim plugin - the most recent version of the plugin supports .slim extensions for templates.