4

Gon 与 Jbuilder 配合得很好。特别是,文档告诉像这样使用它

gon.jbuilder template: 'path/to/template.json.jbuilder'

这很好用,但我想缓存模板结果,所以不需要重新渲染模板。因此,我使用render_to_string了,像这样:

gon.entities = Rails.cache.fetch('entities_json') do
  JSON.parse render_to_string(template: 'path/to/template.json.jbuilder')
end

该方法返回适当的字符串,我必须通过 JSON.parse 传递它,否则该gon变量存储一个双重编码的 JSON 字符串。这很烦人,但我不知道如何解决它。

不幸的是,这个调用render_to_string导致整个 HTML 页面被呈现为一个字符串。HTML 已完成,gon 变量具有预期值,但突然之间,该页面在 Chrome 中不再显示为 HTML。

知道如何解决这个问题吗?

4

2 回答 2

1

看起来您现在可以轻松地使用 Jbuilder 进行片段缓存。这是我在 jbuilder 的源代码中找到的示例:

例子:

json.cache! ['v1', @person], :expires_in => 10.minutes do |json|
  json.extract! @person, :name, :age
end

将此应用于您的代码,我们将在您的控制器中保留以下代码:

gon.jbuilder template: 'path/to/template.json.jbuilder'

然后在您的 jbuilder 视图中,我们将进行片段缓存:

#path/to/template.json.jbuilder
json.cache! ['v1', @model], :expires_in => 10.minutes do |json|
  #your template.json.juilder code in here
end

让我知道它是否有帮助!

于 2013-12-14T17:03:36.037 回答
0

render_to_string更改content_type后续渲染时存在一些问题。见:https ://github.com/rails/rails/issues/14173

一些可能的解决方法是

  • content_type在调用渲染时显式设置,例如render content_type: text/html
  • 显式设置content_type调用后的响应render_to_stringrender_to_string如果您要放入控制器辅助方法并且不希望调用辅助方法的任何人都知道这种怪异,则此选项可能是首选。例如response.headers["Content-Type"] = request.format.to_s
于 2016-11-10T19:20:46.110 回答