LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】Bootstrap3を用いた画像スライドショーの実装

Posted at

目標

ezgif.com-video-to-gif.gif

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Bootstrap3導入
投稿機能実装
画像複数アップロード機能実装

実装

1.ビューを編集

books/show.html.slim
/ 追記
.row
  #sampleCarousel.carousel.slide data-ride='carousel'
    ol.carousel-indicators
      li.active data-target='#sampleCarousel' data-slide-to='0'
      li data-target='#sampleCarousel' data-slide-to='1'
      li data-target='#sampleCarousel' data-slide-to='2'
    .carousel-inner role='listbox'
      - @book.images.each.with_index(1) do |image, index|
        - if index == 1
          .item.active
            = image_tag image.to_s, class: 'img-responsive img-rounded carousel-image'
        - else
          .item
            = image_tag image.to_s, class: 'img-responsive img-rounded carousel-image'
    a.left.carousel-control href='#sampleCarousel' role='button' data-slide='prev'
      span.glyphicon.glyphicon-chevron-left aria-hidden='true'
      span.sr-only
        | 前へ
    a.right.carousel-control href='#sampleCarousel' role='button' data-slide='next'
      span.glyphicon.glyphicon-chevron-right aria-hidden='true'
      span.sr-only
        | 次へ

【解説】

① 本に登録されている画像一覧を繰り返し処理し、indexを付与する。

- @book.images.each.with_index(1) do |image, index|

② 1枚目に表示する画像を設定する。

今回は、indexが 1 の画像を設定しています。

- if index == 1
  .item.active
    = image_tag image.to_s, class: 'carousel-image'

③ 2枚目以降の画像を設定する。

- else
  .item
    = image_tag image.to_s, class: 'carousel-image'

2.application.scssを編集

application.scss
.carousel-image {
  width: 30%; // スライドに対する画像の幅を設定
  margin: 0 auto; // 画像を中央に配置
}
0
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
0
0