Sinatra Gets Slim

Mar 28
comments

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

Slim

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'
  article
    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

Comments

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

Logic-Less

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

Eg.

-post
  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
end

__END__
@@layout
doctype html
html
  head
    title Slim
    meta charset="utf-8"
      
  body
    header
      h1 
       a href="http://slim-lang.com/" Slim
    
    == yield
    
  footer
    small
      | Copyright #{Time.now.year} DAZ

@@index
p
  | 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