Sinatra Gets Slim

Mar 28

Sinatra 1.2 was released a few weeks ago and you can see the full list of all the shiny new additions here.


The thing that got me most excited was a new rendering engine called Slim. This is very similar to Haml that I wrote about a while back, but is even more simple and elegant looking.

You basically just write the tag names, followed by the attributes, followed by the content. Here’s an example:

section class='posts'
    h1= post.title
    a href=post.url Short Url
    p= post.content

As you can see, it just looks really, really nice. I think I’m going to try using it for the next few projects and so far I’m really liking it.

Get It

To use Slim, all you need to do is install the gem:

sudo gem install slim

Then require it in your Sinatra app:

require 'slim'

Escaping HTML

One gotcha that you need to watch out for is that all dynamic HTML is made ‘safe’ by default. This means that all html tags are escaped. This can cause havoc with your paritals, but it is easy to get round - just use the double equal ==.

You can also stop the HTML escaping by changing the default setting:

set :slim, :auto_escape = false


You can add comments to your code using / and HTML comments using /!:

/ This is a comment and won't be in the output
/! This comment will be in the output but as a HTML comment


It also has a nice logic-less mode that only renders code if it exists.


  h1 = title

This will only render the h1 tag if the post object has a title - nice!

Some Code

Here’s a quick example bit of code to show Slim running:

require 'rubygems'
require 'sinatra'
require 'slim'

set :slim, :pretty => true

get '/' do
  slim :index

doctype html
    title Slim
    meta charset="utf-8"
       a href="" Slim
    == yield
      | Copyright #{} DAZ

  | Slim seems a really nice rendering engine.

Notice the setting to show ‘pretty output’ - this just makes sure the HTML that is produced is indented and readable (although it doesn’t always get it right as far as I can see).

I hope you like the look of Slim as much as I do, have a play around with it and let me know what you think in the comments.

blog comments powered by Disqus