LoginSignup
0
2

More than 3 years have passed since last update.

content_tagでmodalやリンクを表示する

Last updated at Posted at 2020-01-18

はじめに

RailsでWebサービスを構築していると、フロントのコードをサーバーサイドで実装する場面ってありますよね。(あんまりないか)
Railsにはcontent_tagというメソッドが用意されていて、フロントのコードをサーバーサイドで記述することができます。

content_tag

content_tagの引数は以下のように構成されています。

  • 第一引数: タグ
  • 第二引数: 内容
  • 第三引数: クラスなどのオプション
# divタグ生成
content_tag(:div, 'hoge', class: 'fuga')
# => <div class="fuga">hoge</div>

modalを表示するには

modal表示のサンプルです。

hoge_helper.rb
def show_modal_button
  content_tag(:a, class: 'btn btn-default form-control', data: { toggle: 'modal', target: '#hoge-modal' }) do
    concat render 'hoge-modal'
    concat 'モーダル表示'
end
hoge/_hoge_modal.html.haml
.modal.fade#hoge-modal
  .modal-dialog
    .modal-content
      .modal-header
        %h4.modal-title
          Title!
      .modal-body
        hogehogefugafuga
      .modal-footer
        .btn.btn-default.data{ dismiss: 'modal' }
          閉じる
hoge/show.html.haml
...
.show-modal
 = show_modal_button
...

リンクを作成する場合

content_tagはlink_toをそのまま扱えないので、以下のように書く必要があります。

fuga_helper.rb
content_tag(a:, class: 'fuga', href: 'https://www.hoge.fuga.com') do
  concat 'hoge&fugaへのリンクです!'
0
2
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
2