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 |
|
Which translates to:
1 2 3 |
|
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 |
|
Or more simply:
1
|
|
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
|
|
Which translates to:
1
|
|
You can create a div with an id by using:
1
|
|
Which translates to:
1
|
|
What about html attributes? Well, we specify them similarly to how we would in html:
1
|
|
Which translates to:
1
|
|
To specify a doctype:
1
|
|
Which translates to:
1
|
|
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 |
|
Which is equivalent to:
1 2 3 4 5 |
|
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
|
|
Which is equivalent to:
1
|
|
Your strings are Rubyized:
1
|
|
You can embed javascript as well:
1 2 |
|
So far so good, That’s it! See ya! :)