关于Rails上的ruby:content_for与片段缓存结合使用的解决方法

Workaround for content_for use in conjunction with fragment caching

我正在尝试按每个元素将内容插入页面的头部,因此我希望能够在部分内容中指定类似的内容:

1
2
3
4
5
6
# _partial.html.erb
<%= content_for :style %>
  .element {
    background-color: red;
  }
<% end %>

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

1
2
3
4
5
6
# application.html.erb
<head>
  <style>
    <%= content_for(:style) %>
  </style>
</head>

但是元素部分是片段缓存的,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


有一个为此打开的Rails拉取请求:https://github.com/rails/rails/pull/39600

希望这很快就会在Rails中"起作用" ... ??

免责声明:我已提交此拉取请求


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

根据设计,在使用缓存时根本不会评估局部变量,因此唯一的解决方案是将content_for结果与\\'real \\'内容一起缓存,就像链接的历史补丁一样。唯一的解决方法是将content_for块移到非局部部分之外-说起来容易做起来容易,并且破坏了首先使用它的意义。

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

这个问题似乎在很多年前就不为人所知了:我在GitHub上根本没有相关的PR。 (我实际上在我的待办事项列表中有关于此的注释,但不知道以前已进行过处理。)

不,没有理由没有实现此功能(如果8年前有原因,它已经被时间束缚了,反正可能不再适用)。如果有人有兴趣追求PR:请这样做。