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。
知道如何解决这个问题吗?
最佳答案
看起来您现在可以使用 Jbuilder 轻松地进行片段缓存。这是我在 jbuilder 的源代码中找到的示例:
例子:
json.cache! ['v1', @person], :expires_in => 10.minutes do |json|
json.extract! @person, :name, :age
end
将此应用于您的代码,我们将在您的 Controller 中保留以下代码:
gon.jbuilder template: 'path/to/template.json.jbuilder'
然后在您的 jbuilder View 中,我们将执行片段缓存:
#path/to/template.json.jbuilder
json.cache! ['v1', @model], :expires_in => 10.minutes do |json|
#your template.json.juilder code in here
end
如果有帮助,请告诉我!
关于javascript - 渲染一个 Jbuilder 模板并将字符串分配给 gon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20505035/