Using the Rails 'flash' with Liquid?

156 views
Skip to first unread message

Paul Hart

unread,
Oct 6, 2009, 10:23:09 PM10/6/09
to Liquid Templates
Hi,

I'm developing a service that allows users to create their own layouts
and views for a variety of different content. I've got this down
pretty well in Liquid so far, using the concept of parsing the view
template and then injecting that into the layout template, but I
haven't figured out how to deal with the flash successfully (yet).

I presume the issue is that I haven't monkey-patched the flash to
enable Liquid to get at the values it contains, but that's just a
presumption. All suggestions welcomed!

Thanks,

Paul

matt

unread,
Oct 8, 2009, 4:37:14 AM10/8/09
to Liquid Templates
I used the following in a liquid filter to get at the flash;

module Liquid
module CommonFilters

# include other helper modules
include ApplicationHelper

# flash message notifications
def notifications(html_id)
if @context.registers[:controller].session && @context.registers
[:controller].session['flash']
html = ""
[:failure, :notice, :success].each do |key|
message = @context.registers[:controller].session['flash']
[key]
html += "<p class=\"#{key}\">#{message}</p>\n" unless
message.blank?
end
return "<div id=\"#{html_id}\">#{html}</div>" unless
html.blank?
end
end

end
end

Works for me; and then in the views use something like;
{{ 'flash' | notifications }}

to give something like;

<div id="myid">
<p class="failure">my failure</p>
<p class="notice">some notice message</p>
</div>

etc.


Of course this will only show the flash keys
matching; :failure, :notice, :success


m


Ps.. heres a test;

it "should show session flash messages" do
@context = Liquid::Context.new
@context.registers[:controller] = ApplicationController.new
@context.registers[:controller].session = Hash.new
notifications('myid').should be_nil
@context.registers[:controller].session['flash'] = {:notice =>
'some notice message'}
notifications('myid').should eql("<div id=\"myid\"><p class=
\"notice\">some notice message</p>\n</div>")

@context.registers[:controller].session['flash'] = {:notice =>
'some notice message', :failure => 'my failure', :unknown => 'blah'}
notifications('myid').should eql("<div id=\"myid\"><p class=
\"failure\">my failure</p>\n<p class=\"notice\">some notice message</p>
\n</div>")
end
Reply all
Reply to author
Forward
0 new messages