Andy Harvey
Andy Harvey

Reputation: 12653

How to render HTML and Rails helpers in a Devise flash message?

I'm trying to render a custom flash message from a Devise controller.

It is being rendered in the view as follows:

<strong>Your profile is incomplete.</strong> Why not #{ActionController::Base.helpers.link_to 'add some more information', edit_user_registration_path}.

How do I render HTML and Rails helpers in this flash?

I'm calling the flash in the controller

set_flash_message :warning, :profile_incomplete

With :profile_incomplete defined in config/locales/devise.en.yml.

I tried putting the string directly in the controller. This correctly renders the helper, but instead displays a Devise translation not found error.

I have tried appending .html_safe in devise.en.yml, which causes a yaml error. I've tried appending to :profile_incomplete which causes undefined method 'html_safe' for :profile_incomplete:Symbol. And I've tried appending to the plain string, which didn't seem to do anything.

What am I missing? Thanks for any suggestions.

EDIT

sessions_controller.rb

def after_sign_in_path_for(resource)

  if current_user.completeness < 100
    set_flash_message :alert, :profile_incomplete, :link => ActionController::Base.helpers.link_to('add some more information', edit_user_registration_path)
  end

end

devise.en.yml

en:
  devise:
    sessions:
      profile_incomplete:"<strong>Your profile is incomplete.</strong> Why not #{link}."

application.html.erb

<% flash.each do |key, msg| %>
    <div class="alert alert-<%= key %>">
        <a class="close" data-dismiss="alert">x</a>
        <%= msg.html_safe %>
    </div>
<% end %>

Upvotes: 2

Views: 3010

Answers (1)

Cristian Bica
Cristian Bica

Reputation: 4117

this is the source of set_flash_message: https://github.com/rymai/devise_invitable/blob/master/lib/devise_invitable/controllers/internal_helpers.rb#L5

You cannot add methods in i18n files .. just named interpolations. My solution for your problem is:

set_flash_message :warning, :profile_incomplete, :link => link_to('add some more information', edit_user_registration_path)

and in devise.en.yml

...
profile_incomplete: "<strong>Your profile is incomplete.</strong> Why not %{link}"

also when displaying the flash message (probably in application.html.erb/haml) add a html_safe at the end of each flash message

Upvotes: 4

Related Questions