我希望比在YAML文件中添加链接到Flash消息(例如已登录的用户名等)更加灵活,因此我想在字符串中使用ERB标记。 我正在使用
bootstrap_flash
,因此我修改了辅助代码如下以解码ERB字符串在显示之前:
require 'erb'
module BootstrapFlashHelper
ALERT_TYPES = [:error, :info, :success, :warning] unless const_defined?(:ALERT_TYPES)
def bootstrap_flash
flash_messages = []
flash.each do |type, message|
next if message.blank?
type = type.to_sym
type = :success if type == :notice
type = :error if type == :alert
next unless ALERT_TYPES.include?(type)
Array(message).each do |msg|
begin
msg = ERB.new(msg).result(binding) if msg
rescue Exception=>e
puts e.message
puts e.backtrace
end
text = content_tag(:div,
content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
msg.html_safe, :class => "alert fade in alert-#{type}")
flash_messages << text if msg
end
end
flash_messages.join("\n").html_safe
end
end
接下来可以使用类似以下的字符串(使用devise):
signed_in: "Welcome back <%= current_user.first_name %>! <%= link_to \"Click here\", account_path %> for your account."
这种方法并不适用于所有情况,也有人认为代码和字符串定义不应混合(特别是从DRY的角度),但对我来说似乎很有效。该代码应适用于许多其他情况,其中关键部分如下:
require 'erb'
....
begin
msg = ERB.new(msg).result(binding) if msg
rescue Exception=>e
puts e.message
puts e.backtrace
end