0
0

More than 1 year has passed since last update.

flashに複数行を表示する方法について

Last updated at Posted at 2022-09-29

環境

Rails5.2
Ubuntu20.4
Bootstrap5

はじめに

flashに複数行を改行付でセットし、BootstrapのAlertに、箇条書きで表示する方法について書いてみました。

解説

flashに表示する複数のメッセージを、msg変数にセットします。

test_controller.rb
msg = []
msg << "メッセージ1"
msg << "メッセージ2"
msg << "メッセージ3"

msg配列から1要素づつ取得して、notice変数に文字列としてセットします。文字列の最後に、HTMLの改行brをセットします。brはmsg配列の最後の要素にはセットしません。

test_controller.rb
msg.each_with_index do |val, idx|
    notice += "・ " + val
    notice += "<br>" unless (msg.length == idx + 1)
end
flash[:notice] = notice
redirect_to test_url

HTMLのbrを有効にするために、html_safeを付加します。html_safeをつけなければ、brが文字列として表示されることになります。

application.html.slim
- if flash.notice.present?
	.alert.alert-success = flash.notice.html_safe

表示のされ方

無題.png

0
0
2

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