Slim on Rails

Slim on Rails

The first thing you need to do is add a couple gems to the Gemfile. The slim gem tells Rails how to parse the Slim syntax. The slim-rails gem overrides the Rails generators for ERB and replaces them with Slim generators. Add these gems to your Gemfile as below:

Gemfile
1
2
gem 'slim', '~> 2.0.3'
gem 'slim-rails', '~> 2.1.5'

Then run bundle install to install the gems:

1
bundle install

Then generate a Homes controller with a show action by running the command below:

1
rails g controller Homes show

Notice that the generated view ends in .slim, Rails has generated a slim file for us, courtesy of the slim-rails gem. Now let’s modify our routes file to set up a resource and add a root path. Open up your routes file (config/routes.rb) and modify it so that it looks somethings like:

routes.rb
1
2
root to: "homes#show"
resource :home, only: [:show]

Now you are ready to play with Slim. Open up the show view for homes (app/views/homes/show.html.slim) and modify it so that it looks somethings like:

show.html.slim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
javascript:
  alert("HELLO!!!!!")
h1 Welcome to my site
<b>inline html is supported</b>
p
  | The time is #{ Time.now }, 
    I Like to program in Ruby on Rails.
#hashtag I threw a hashtag in here!
#classy I'm classy!

p = Random.rand(10)

- if Random.rand(6) == 1
  |Lucky number 1!  You win!
br
br
small Goodbye!

Which translates to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript">
  alert("HELLO!!!!!")
</script>

<h1>Welcome to my site</h1>
<b>inline html is supported</b>
<p>The time is 2015-02-22 00:24:59 - 0400, I Like to program in Ruby on Rails.</p>

<div id="hashtag">
  I threw a hashtag in here!
</div>

<div id="classy">
  I'm classy!
</div>

<p>2</p>
<br>
<br>
<small>Goodbye!</small>

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