9
6

More than 5 years have passed since last update.

【Rails】content_tagを使って定番の表示画面をhelper化する

Last updated at Posted at 2019-07-02

content_tag

content_tagという便利なメソッドを知ってしまった。
これにより、htmlタグを生成することができる。

content_tagに関して、詳しくは以下を参照↓
http://railsdoc.com/references/content_tag
https://kana-linux.info/rails/rails%E3%81%AEview-helper%E3%81%A7html%E3%82%BF%E3%82%B0%E3%82%92%E5%87%BA%E5%8A%9B%E3%81%99%E3%82%8B

content_tagを使ってhtmlをhelperで作成

bootstrapと併用して、割と定番的に使うもの↓

flash[:notice], flash[:alert]

users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to toppage_path, notice: "success"
  else
    render 'new'
  end
end
toppage.html.erb
<% if flash[:notice] %>
  <div class="container">
    <div class="alert alert-success">
      <%= flash[:notice] %>
    </div>
  </div>
<% end %>
<% if flash[:alert] %>
  <div class="container">
    <div class="alert alert-danger">
      <%= flash[:alert] %>
    </div>
  </div>
<% end %>

viewでこのように書くことが多いと思われるflash[:notice]flash[:alert]だが、
helperで記述すると、↓

application_helper.rb
  def notice_msg
    if flash[:notice]
      content_tag(:div, class: "container") do
        content_tag(:div, class: "alert alert-success") do
          flash[:notice]
        end
      end
    end
  end
  def alert_msg
    if flash[:alert]
      content_tag(:div, class: "container") do
        content_tag(:div, class: "alert alert-danger") do
          flash[:alert]
        end
      end
    end
  end
toppage.html.erb
<%= notice_msg %>
<%= alert_msg %>

こんな感じでviewテンプレートの行数が圧縮できた。

errors.full_messages

バリデーションのエラーメッセージを表示する、典型的なやつです。

users_controller.rb
def create
  @user = User.new(user_params)
  if @user.save
    redirect_to toppage_path, notice: "success"
  else
    render 'new'
  end
end
new.html.erb

<%= @user.errors.full_messages.each do |msg| %>
  <div class="alert alert-danger">
    <%= msg %>
  </div>
<% end %>
<%= form_with model: @user, local: true do |f| %>
・
・

このように書くことが多いと思われるerrors.full_messagesですが、helperで記述します↓

application_helper.rb
  def errors_full_messages(var)
    var.errors.full_messages.each do |msg|
      concat (content_tag(:div, class: "alert alert-danger") do
        msg
      end)
    end
  end

↑()の使い方が汚いですが・・・

new.html.erb

<% errors_full_messages(@user) %>
<%= form_with model: @user, local: true do |f| %>
・
・

引数に該当するインスタンス変数を指定すれば使えます。
こんな感じでviewの行数が圧縮できました。
あとはi18nで設定を加えれば、以下のように表示されます。
スクリーンショット 2019-07-02 12.08.38.png

感想

他にもよく使うviewで定番的に使うものは、helperでテンプレート化したい。

9
6
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
9
6