Slim Template Language

Slim Template Language

Slim is a replacement for ERB, similar to HAML. Slim provides a nice lean syntax that’s easy to pick up and learn. In this article we will learn how to use Slim. Let’s run through this with me.

Basic Syntax
Slim is actually really easy to learn. Indentation matters, but the indentation depth can be chosen as you like. If you want to first indent 2 spaces, then 5 spaces, it’s your choice.

Example:

1
2
p
  | This is a very long paragraph

Which translates to:

1
2
3
<p>
  This is a very long paragraph.
</p>

In the above example you’ll notice two things. First, the pipe (|) character is used to delimit free-form text on a new line. Second, we simply used p to specify the paragraph tag. This works for any tag, for instance you could just as easily have done:

1
2
h1
  | Large Title

Or more simply:

1
h1 Large Title

In the above example that we didn’t specify the pipe (|) character. The pipe (|) character is only needed if we are entering free-form text on a new line.

You can create a div with a default class by using:

1
class

Which translates to:

1
<div class="class"></div>

You can create a div with an id by using:

1
#id

Which translates to:

1
<div id="id"></div>

What about html attributes? Well, we specify them similarly to how we would in html:

1
meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"

Which translates to:

1
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"></meta>

To specify a doctype:

1
doctype html

Which translates to:

1
<!DOCTYPE html>

Well, all is great, but what about Ruby code? Inserting Ruby code is pretty easy. Code that doesn’t return a result, such as if statements or loops, are prefixed with a dash (-).

1
2
- if @products.nil?
  p No results found. Please try again.

Which is equivalent to:

1
2
3
4
5
if @products.nil?
  <p>
    No results found.  Please try again.
  </p>
end

Slim will auto close your Ruby code as well, so end isn’t needed.

If you have code that returns output, such as the printing of a variable or property, you can use the equal (=) sign.

1
= current_user.name

Which is equivalent to:

1
<%= current_user.name %>

Your strings are Rubyized:

1
| Hello #{user.name}

You can embed javascript as well:

1
2
javascript:
  alert("hello world!")

So far so good, That’s it! See ya! :)