LoginSignup
6

More than 3 years have passed since last update.

[Rails]テンプレートエンジン(haml.slim)の導入方法と書き方

Last updated at Posted at 2020-04-09

パフォーマンス比較グラフ

20170910222126.png

erb(比較用)

~.html.erb
<h1>Users</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.name %></td>
        <td><%= user.email %></td>
        <td><%= link_to 'Show', user %></td>
        <td><%= link_to 'Edit', edit_user_path(user) %></td>
        <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New User', new_user_path %>

haml

1.導入方法

Gemfile
gem 'haml-rails' #hamlファイルを使えるようにする
ターミナル
$ bundle
ターミナル
$ rails haml:erb2haml
ターミナル
<!-- 下記の様に問われるので、既存のerbファイルを削除してもいいなら「y + Enter」、駄目なら 「n + Enter」 -->
Would you like to delete the original .erb files? (This is not recommended unless you are under version control.) (y/n)

既存のerbファイルをhamlファイルに変換

2.書き方

~.html.haml
%h1 Users

%table
  %thead
    %tr
      %th Name
      %th Email
      %th

  %tbody
    - @users.each do |user|
      %tr
        %td = user.name
        %td = user.email
        %td = link_to 'Show', user
        %td = link_to 'Edit', edit_user_path(user)
        %td = link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' }

%br

= link_to 'New User', new_user_path

slim

1.導入方法

Gemfile
gem 'slim-rails' #slimファイルを使えるようにする
gem 'html2slim' #既存のerbファイルをslimファイルに変換出来る様にする
ターミナル
$ bundle

既存のerbファイルをslimファイルに変換し、erbファイルを全削除する。

ターミナル
$ bundle exec erb2slim app/views app/views -d

ビューを作成時、自動的にslimに変換する。

application.rb
module Devise
  class Application < Rails::Application
    config.load_defaults 5.2
    config.generators.template_engine = :slim #追記
  end
end

2.書き方

~.html.slim
h1 Users

table
  thead
    tr
      th Name
      th Email
      th

  tbody
    - @users.each do |user|
      tr
        td = user.name
        td = user.email
        td = link_to 'Show', user
        td = link_to 'Edit', edit_user_path(user)
        td = link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' }

br

= link_to 'New User', new_user_path

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6