Railsでslimを使ってみる

September 08, 2022

確認環境

$ bundle exec ruby --version
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin19]
$ bundle exec rails --version
Rails 6.0.4.6

slim-rails をインストール

Gemfile

gem 'slim-rails'
$ bundle install

設定を更新: generate時にslimを使う

config/application.rb

module Sample6
  class Application < Rails::Application
    config.load_defaults 6.0

    config.generators.template_engine = :slim

    ...
  end
end

ファイルの準備

$ rails g controller Hoge2 index
      create  app/controllers/hoge2_controller.rb
       route  get 'hoge2/index'
      invoke  slim
      create    app/views/hoge2
      create    app/views/hoge2/index.html.slim
      invoke  rspec
      create    spec/requests/hoge2_request_spec.rb
      create    spec/views/hoge2
      create    spec/views/hoge2/index.html.slim_spec.rb
      invoke  helper
      create    app/helpers/hoge2_helper.rb
      invoke    rspec
      create      spec/helpers/hoge2_helper_spec.rb
      invoke  assets
      invoke    scss
      create      app/assets/stylesheets/hoge2.scss
$ rails g model Hoge2 name:string
      invoke  active_record
      create    db/migrate/20220829160249_create_hoge2s.rb
      create    app/models/hoge2.rb
      invoke    rspec
      create      spec/models/hoge2_spec.rb
      invoke      factory_bot
      create        spec/factories/hoge2s.rb
$ rake db:migrate
== 20220829160249 CreateHoge2s: migrating =====================================
-- create_table(:hoge2s)
   -> 0.0026s
== 20220829160249 CreateHoge2s: migrated (0.0028s) ============================

config/routes.rb

get  "hoge2/index"  => "hoge2#index"

view を修正してみる

app/views/hoge2/index.html.slim

 h1 Hoge2#index
 p Find me in app/views/hoge2/index.html.slim

 ul
   li part1
   li part2
   li part3

参考


SHARE

Profile picture

Written by tamesuu