Gon integration with Jbuilder is seamless. According to the documentation, the recommended approach is to use it as follows:
gon.jbuilder template: 'path/to/template.json.jbuilder'
While this method works well, I wanted to optimize by caching the template result to avoid re-rendering each time. To achieve this, I utilized render_to_string
in the following manner:
gon.entities = Rails.cache.fetch('entities_json') do
JSON.parse render_to_string(template: 'path/to/template.json.jbuilder')
Although the function returns the correct string, it necessitates passing it through JSON.parse to prevent double-encoded JSON. This extra step can be frustrating, but I have not found an alternative solution yet.
However, using render_to_string
leads to rendering the entire HTML page as a string. While the gon variables contain the expected values, Chrome suddenly stops displaying the content as HTML.
If you have any suggestions on how to resolve this issue, please share your insights.