How can I render one partial twice in jbuilder?

416 Views Asked by At

I want to render a jbuilder template like this:

json.author do
  json.partial! 'user', user: @user
end
json.owner do
  json.partial! 'user', user: @user
end

It seems a waste to render one partial twice, can I render like this?

user_json = json.some_render_partial! 'user', user: @user
json.author { user_json }
json.owner { user_json }
1

There are 1 best solutions below

0
On

It seems a waste to render one partial twice, can I render like this?

If your concern is to minimize code then yes, you can using procs.

user_json = proc { json.partial! 'user', user: @user }

json.author &user_json
json.owner &user_json

Also, if your concern is to boost performance, then one way is to cache your partial. Try this

user_json = proc {
  json.cache! @user, expires_in: 10.minutes do
    json.partial! 'user', user: @user
  end
}

json.author &user_json
json.owner &user_json

But, sometimes caching can be slower instead. So, keep in mind if it meets the following criteria:

  • Partial encompasses hefty computation that are on average more expensive than accessing cache. like WEB API Calls or AR queries

  • The size of the JSON blob produced is small

See this for more info [ Jbuilder Rails caching is slower ]