LoginSignup
2
0

More than 3 years have passed since last update.

slimの始め方

Posted at

slimのインストール

アプリのフォルダ内でslimをインストールする。

gem install slim

これで拡張子が.html.slimのslimファイルを、みなさんが普段使っている.html.erbとして変換されるようになるそうです。

gem install html2slim

これでhtml.erb → html.slim に変換させることができるようになるそうです。

bundle exec erb2slim app/views app/views

これでエラーが出た場合は、gemfileに下記の2文を追加してbundle installします。

gem 'slim-rails'
gem 'html2slim'
bundle install

これでviewフォルダに元からあったerbファイルを削除するそうです。
※拡張子が.erbのファイルがない場合は、飛ばしてよし。

bundle exec erb2slim app/views app/views -d

今後自動的にslimファイルを作成されるようにするためには 、
config/application.rbにあるconfigを以下のようにslimを指定すればOK。

config/application.rb
module App
  class Application < Rails::Application
    config.generators.template_engine = :slim #slimに変更
  end                                                                                                                                                                     
end

slimファイルを表示させる前の準備

rails g controller tweets

viewフォルダのなかに、tweetsフォルダができています。
そのなかにindex.html.slimというファイルを新しく作ります。
そのファイルの中に分かりやすいように何か書いておきましょう。

views/tweets/index.html.slim
Hello, world!

コントローラーの中にindexアクションを追加しておきます。

controllers/tweets_controller.rb
class ArchivesController < ApplicationController
    def index
    end
end

次にルーティングです。

config/routes.rb
Rails.application.routes.draw do
  root "tweets#index"
end

サーバーを再起動して、ページを表示

サーバーの再起動を忘れないようにしましょう。
再起動しないままだと、「ArchivesController#index is missing a template for request formats: text/html」というようなエラーが出ます。

参考記事

2
0
0

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
2
0