content_for 与片段缓存结合使用的解决方法

ora*_*tea 4 caching ruby-on-rails fragment-caching content-for ruby-on-rails-5.1

我试图在每个元素的基础上将内容插入我的页面的头部,所以我希望能够在部分指定这样的内容:

# _partial.html.erb
<%= content_for :style %>
  .element {
    background-color: red;
  }
<% end %>
Run Code Online (Sandbox Code Playgroud)

并将其放在我的页面的头部:

# application.html.erb
<head>
  <style>
    <%= content_for(:style) %>
  </style>
</head>
Run Code Online (Sandbox Code Playgroud)

但是元素部分是片段缓存的,content_for在缓存中被忽略。

它在 Rails 文档中声明content_for不会用于片段缓存的工作元素:

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

目前有没有办法content_for在 Rails 5.1 上使用片段缓存?似乎已经有一段时间没有人真正触及这个问题了。有谁知道是否有原因?


这里有一些较旧的提及:

是否有使用 caches_action 和 :layout => false 忽略 content_for 块的解决方法?

content_for 可用于开发但不能用于生产?

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

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

Tyl*_*ick 5

现在有这个开放的 Rails 拉取请求:https : //github.com/rails/rails/pull/39600

希望这将很快在 Rails 中“正常工作”......

免责声明:我提交了这个拉取请求