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]
def create
@user = User.new(user_params)
if @user.save
redirect_to toppage_path, notice: "success"
else
render 'new'
end
end
<% 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で記述すると、↓
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
<%= notice_msg %>
<%= alert_msg %>
こんな感じでviewテンプレートの行数が圧縮できた。
errors.full_messages
バリデーションのエラーメッセージを表示する、典型的なやつです。
def create
@user = User.new(user_params)
if @user.save
redirect_to toppage_path, notice: "success"
else
render 'new'
end
end
<%= @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で記述します↓
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
↑()の使い方が汚いですが・・・
<% errors_full_messages(@user) %>
<%= form_with model: @user, local: true do |f| %>
・
・
引数に該当するインスタンス変数を指定すれば使えます。
こんな感じでviewの行数が圧縮できました。
あとはi18n
で設定を加えれば、以下のように表示されます。
感想
他にもよく使うviewで定番的に使うものは、helperでテンプレート化したい。