Problem/Motivation
The existing pattern for checking if a view returns results executes the view twice. Even when the results are cached, the view is built twice.
#2925554: Add drupal_view_result() function introduced drupal_view_result and a suggested pattern (as documented in view.md) that first executes the view to determine if there are any results, and then executes it again to get the results.
Proposed resolution
A better pattern would be to execute it only once and hide the results if nothing is found.
The attached patch modifies drupal_view to do just that, using jQuery and a class that can be placed on parent divs to hide.
In my testing, this saved about 200msec per page view (we have a lot of views and used this pattern a lot).
User interface changes
No change is necessary. But if sites want to take advantage of the improved performance, they'll need to change their twig files to the new pattern.
Comment | File | Size | Author |
---|
Comments
Comment #2
douggreen CreditAttribution: douggreen commentedComment #3
Chi CreditAttribution: Chi commentedThat seems too specifc. There are cases when attachments are not processed, i.e. email templates.
Also this not only about hiding empty wrappers. The one may want to provide alternative content when the view is empty. Say fallback view.
Comment #4
douggreen CreditAttribution: douggreen commentedWhat do you mean by email templates? Views already gives you empty handlers, such as providing another view.
The pattern is still expensive and I've noticed that our themers use it even when there is nothing to hide.
Comment #5
Chi CreditAttribution: Chi commentedTwig templates that are used for crafting email content.
Comment #6
Chi CreditAttribution: Chi commentedThat's just an example. People may have different use cases besides hiding wrapper, i.e. showing differenent content, changing layout, etc.
I think dealing with emptiness is out of scope of the
drupal_view()
The difficulty of checking empty render arrays is a well know Drupal theming issue. It's not specific to Twig Tweak and it is not only about views. Same issue exists for blocks and regions. See #953034: [meta] Themes improperly check renderable arrays when determining visibility.Comment #7
douggreen CreditAttribution: douggreen commentedok, I think that the documentation can be updated to give better examples on when this is necessary.
I'm going to apply my solution as custom js to our projects, as this is always the behavior we want.
for anyone else trying this solution, note that we discovered that adding the #attached in drupalView here causes problems. The better solution is to add it from hook_views_post_render(). But since this solution isn't going to be considered here, I am not updating the patch.
Comment #8
Chi CreditAttribution: Chi commentedCSS :has selector will help to deal with empty regions. Modern browsers already support it though FF still keeps it behind a flag.