ruby-on-railscachingruby-on-rails-5.1fragment-cachingcontent-for

Workaround for content_for use in conjunction with fragment caching


I'm trying to insert content into the head of my page on an per element basis, so I'd like to be able to specify something like this in a partial:

# _partial.html.erb
<%= content_for :style %>
  .element {
    background-color: red;
  }
<% end %>

And place that in the head of my page:

# application.html.erb
<head>
  <style>
    <%= content_for(:style) %>
  </style>
</head>

But the element partials are fragment cached, content_for is ignored in caches.

It's stated in Rails documentation that content_for will not for work elements that are fragment cached:

WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached. http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

Is there currently a way to get content_for to work with fragment caching on Rails 5.1? No ones seems to have really touched this issue for a while. Does anyone know if there's a reason why?


There are some older mentions here:

Is there a workaround for ignored content_for blocks with caches_action and :layout => false?

content_for works in development but not production?

https://gist.github.com/stackng/891895

https://rails.lighthouseapp.com/projects/8994/tickets/3409-content_for-and-fragment-caching


Solution

  • Is there currently a way to get content_for to work with fragment caching on Rails 5.1?

    By design, the partial is not evaluated at all when the cache is used, so the only solution would be to cache the content_for result along with the 'real' content, as the linked historical patch did. The only work-around is to move the content_for block outside the partial -- which is understandably easier said than done, and undermines the point of using it in the first place.

    No ones seems to have really touched this issue for a while. Does anyone know if there's a reason why?

    It looks like the issue just fell off the radar many years ago: I see no relevant PR in GitHub at all. (I actually have a note about this in my personal todo list, but had no idea it had previously been worked on.)

    No, there is no reason why this functionality hasn't been implemented (if there was a reason 8 years ago, it's been lost to the sands of time -- and may no longer apply anyway). If someone's interested in pursuing a PR: please do.