Rails6.1ハンズオン(2)～見た目をそれっぽくする

# はじめに

[Rails6.1ハンズオン(1)](https://qiita.com/Hirororocky/items/725a6e39785359e9b3b3)の続きです。

環境は[これ](https://qiita.com/Hirororocky/items/d5a035a2a1a7961cf12a)を参考にしてください。

コードは[Github](https://github.com/hirorocky/Rails6.1_hands_on)にあげています。章ごとにコミットしてますので、参考にしていただければ幸いです。

# やること

- erbからhamlにする
- Bootstrap 5.0.0.beta2(2021/2/22時点)を入れる
- Font Awesomeを入れる
- i18nを使って日本語化
- 見た目をいい感じに整える

# 実装

## 3-1. erbからhamlにする

Gemfileに

```ruby
gem 'haml-rails'
```

を追加。bundle install。

```bash
rails haml:erb2haml
```

で、プロジェクト内のerbをhamlに一斉変換できる。（最後に元のerbを消していいか聞かれるのでyを入力）

## 3-2. Bootstrap 5.0.0.beta2を入れる

参考：

[Use Bootstrap 5 with Ruby on Rails 6 and webpack step by step](https://medium.com/daily-web-dev/use-bootstrap-4-with-ruby-on-rails-6-and-webpack-fe7300604267)

ターミナルで以下のコマンドを入力

```bash
yarn add bootstrap@next
yarn add @popperjs/core
```

app/views/layouts/application.html.hamlのstylesheet_link_tagの行を以下に置換

```haml
= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
```

app/javascript/stylesheets/application.scssを作成

```scss
@import "bootstrap";
```

を追加。

app/javascript/packs/application.js

```js
import "bootstrap"
import "../stylesheets/application"
```

を追加。

## 3-3. Font Awesomeを入れる

```bash
yarn add @fortawesome/fontawesome-free
```

app/javascript/stylesheets/application.scss

```scss
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
```

を追加。

app/javascript/packs/application.js

```ruby
import '@fortawesome/fontawesome-free/js/all'
```

を追加

## 3-4. 日本語化

参考：

[[初学者]Railsのi18nによる日本語化対応 - Qiita](https://qiita.com/shimadama/items/7e5c3d75c9a9f51abdd5)

config/application.rbに以下を追加

```ruby
config.time_zone = 'Tokyo'
config.i18n.default_locale = :ja
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
```

config/locales/model.ja.ymlを作成

```yaml
ja:
  activerecord:
    models:
      community: コミュニティ 
      comment: コメント
    attributes:
        community:
          id: ID
          title: タイトル
          owner_name: 作成者
        comment:
          id: ID
          author_name: 投稿者
          content: 内容
  attributes:
    created_at: 作成日
    updated_at: 更新日
```

[svenfuchs/rails-i18n](https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/ja.yml)

↑ここからconfig/locales/ja.ymlを作成

locales/views/以下にもyamlファイルを作りますが、詳しくはgithubにて...

## 3-5. 見た目を色々整える

app/javascript/stylesheets/application.scss

```scss
@import '~@fortawesome/fontawesome-free/scss/fontawesome';

$primary: #9400d9; //Bootstrapの変数をいじる
@import "bootstrap";
```

app/controllers/communities_controller.rb

```ruby
def show
  @community = Community.find(params[:id])
  @comments = @community.comments.order(created_at: :desc) # 投稿日：降順で並び替え
end
```

app/views/layouts/application.html.haml

```haml
!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
    %title Rails61HandsOn
    %meta{:content => "width=device-width,initial-scale=1", :name => "viewport"}/
    = csrf_meta_tags
    = csp_meta_tag
    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
    = stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
  %body
    = render '/layouts/header'
    .container-fluid.pt-4.px-4
      = yield
```

app/views/layouts/_header.html.haml

```haml
%nav.navbar.navbar-expand-lg.navbar-dark.bg-dark
  .container-fluid
    = link_to root_path, class: 'navbar-brand' do
      Rails6.1掲示板
    %button.navbar-toggler{"aria-controls" => "navbarSupportedContent", "aria-expanded" => "false", "aria-label" => "Toggle navigation", "data-bs-target" => "#navbarSupportedContent", "data-bs-toggle" => "collapse", :type => "button"}
      %span.navbar-toggler-icon
    #navbarSupportedContent.collapse.navbar-collapse
      %ul.navbar-nav.me-auto.mb-2.mb-lg-0
        %li.nav-item
          = link_to root_path, class: 'nav-link' do
            トップ
        %li.nav-item
          = link_to new_community_path, class: 'nav-link' do
            コミュニティを作る
```

app/views/communities/index.html.haml

```haml
.d-flex.justify-content-between.align-items-center.mb-4
  %h1= t('.title')
  = link_to new_community_path, class: 'btn btn-primary' do
    %i.fas.fa-plus
    = t('.link_to_new')

.container-fluid
  .row
    - @communities.each do |community|
      .col-md-6.col-lg-4.p-1
        .card
          .card-body
            %h4= community.title
            %div= t('activerecord.attributes.community.owner_name') + '：' + community.owner_name
            .d-flex.justify-content-between
              %div= t('activerecord.attributes.community.created_at') + '：' + l(community.created_at)
              = link_to community_path(community) do
                %i.fas.fa-arrow-right
                中に入る
```

app/views/communities/new.html.haml

```haml
%h1= t('.title')
= form_with model: @community do |form|
  = form.label :title, class: 'form-label'
  = form.text_field :title, class: 'form-control mb-2'
  = form.label :owner_name, class: 'form-label'
  = form.text_field :owner_name, class: 'form-control mb-4'
  = form.submit '作成', class: 'btn btn-primary'
```

Bootstrap5.0からは.form-groupがなくなるらしい。その代わりに.mb-3を使ってとのこと。（今回はmb-2にしてますが）

[twbs/bootstrap](https://github.com/twbs/bootstrap/blob/main/site/content/docs/5.0/migration.md)

> Dropped .form-group for margin utilities (we've replaced our docs examples with .mb-3).

app/views/communities/show.html.haml

```haml
= link_to communities_path, class: 'btn btn-light mb-3' do
  %i.fas.fa-arrow-left
  戻る

.container
  %h1= t('.title', title: @community.title)
  = link_to new_community_comment_path(@community), class: 'btn btn-primary' do
    %i.fas.fa-comment
    = t('.link_to_new_comment')

  %ul.list-group.mt-4
    - @comments.each do |comment|
      %li.list-group-item
        .fs-5= comment.author_name
        .fs-6.mb-3= l(comment.created_at, format: :long)
        .fs-6= simple_format(comment.content)
```

.fs-*というクラスも増えてる。フォントサイズが変えられる。

app/views/comments/new.html.haml

```haml
= link_to community_path(@community), class: 'btn btn-light mb-3' do
  %i.fas.fa-arrow-left
  戻る

.container
  %h1= t('.title', community_title: @community.title)
  = form_with model: [@community, @comment] do |form|
    = form.label :author_name, class: 'form-label'
    = form.text_field :author_name, class: 'form-control mb-2'
    = form.label :content, class: 'form-label'
    = form.text_area :content, class: 'form-control mb-4'
    = form.submit '投稿', class: 'btn btn-primary'
```
こんな感じになりました↓
![localhost_3000_communities.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/70400/1d647625-13c9-1d85-adb9-b30f3a0c965a.png)

次回：
[Rails6.1ハンズオン(3)～ユーザー機能編](https://qiita.com/Hirororocky/items/f0640eabc3d9a862c27e)