Search⌘ K
AI Features

Creating HTML Templates with Slim

Explore how to use Slim as a lightweight templating language in Rails, replacing ERB to create more readable and compact HTML templates. Learn to install slim-rails, convert existing templates, and leverage Rails generators to build efficient views.

We'll cover the following...

Slim template

Slim is a templating language that can replace ERB. It’s designed to require much less code to achieve the same results, and it does this by using a nested structure instead of HTML tags. Consider this ERB:

HTML
<h2><%= t('.title') %></h2>
<table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
</tr>
</table>

In Slim, this would look like so:

Ruby
h2
= t('.title') table
= render(cart.line_items)
tr.total_line
td.colspan=2
Total
td.total_cell
= number_to_currency(cart.total_price)

Slim treats each line as an opening HTML tag, and anything indented under that line will be rendered inside that tag. Helper methods and instance variables can be accessed using =, like so:

Ruby
ul
li = link_to @product.name, product_path(@product)

To execute logic such as looping ...