刘华佼的全栈学习记录

如何制作提示信息

| Comments

先上效果图:

制作提示信息的步骤概览:

  • 挂提示套件:app/assets/javascripts/application.js加入://= require bootstrap/alert
  • 新增app/views/common/_flashes.html.erb
  • 新增app/helpers/flashes_helper.rb
  • 修改app/views/layout/application.html.erb,加上partial:flashes
  • 在app/controller/welcome_controller里增加flash语句测试。

具体步骤如下:

第一步

将bootstrap的js提示套件bootstrap/alert挂进项目里面
在app/assets/javascripts/application.js
加入:
//= require bootstrap/alert

第二步

新增app/views/common/_flashes.html.erb

<% if flash.any? %>
  <% user_facing_flashes.each do |key, value| %>
    <div class="alert alert-dismissable alert-<%= flash_class(key) %>">
      <button class="close" data-dismiss="alert">×</button>
      <%= value %>
    </div>
  <% end %>
<% end %>

第三步

新增app/helpers/flashes_helper.rb

module FlashesHelper
  FLASH_CLASSES = { alert: "danger", notice: "success", warning: "warning"}.freeze

  def flash_class(key)
    FLASH_CLASSES.fetch key.to_sym, key
  end

  def user_facing_flashes
    flash.to_hash.slice "alert", "notice", "warning" 
  end
end

第四步

修改app/views/layout/application.html.erb,加上partial:flashes:

<%= render "common/flashes" %>
<%= yield %>

第五步

测试:在app/controller/welcome_controller里增加:

  def index
    flash[:notice] = "Good day, huh?"
  end

效果图:

小结

  • 挂提示套件:app/assets/javascripts/application.js加入://= require bootstrap/alert
  • 新增app/views/common/_flashes.html.erb
  • 新增app/helpers/flashes_helper.rb
  • 修改app/views/layout/application.html.erb,加上partial:flashes
  • 在app/controller/welcome_controller里增加flash语句测试。

Comments

comments powered by Disqus