When you use caches_action :layout => false
in Rails 3, any content_for blocks that are populated in the cached view and used in your layout wind up empty. Is there any workaround for this?
E.g. in my application I have the following rather typical setup.
A helper method called from my views which sets the page title:
# application_helper.rb def page_title(title) content_for(:page_title) { title } end
A line in my layout file as follows
# application.html.erb <head> <title><%= yield(:page_title) %></title> </head>
And in a view I might call
# index.html <% page_title 'Hello!' %>
Of course, if you cache your action with :layout => false
, this results in having blank page titles, since action caching ignores all content_for blocks.
Is there no workaround for this? Action caching with :layout => false
is so close to being brilliantly useful, but this glitch renders it quite awkward.
Other folks asking or commenting about this same issue:
And the Rails documentation that notes this behavior:
"WARNING: content_for is ignored in caches. So you shouldn’t use it for elements that will be fragment cached."
I believe the way I got around this was to create a fragment cache of the parts of the header that are dependent on the content_for being populated.
so it looks something like this:
# application.html.erb <head> <% cache("#{request.env['PATH_INFO']}/header") do %> <title><%= yield(:page_title) %></title> <% end %>
so this cached fragment should be populated at the same time the action is cached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With