简体   繁体   中英

How can I render one partial twice in jbuilder?

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 }

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 proc s.

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM