What is the proepr way to use drupal_view_result()?

Created on 30 January 2025, 3 months ago

Problem/Motivation

Is this the best way to use show a View only when it has content?

{% if drupal_view_result('related', 'block_1') is not empty %}
  <section>
    {{ drupal_view('related', 'block_1') }}
  </section>
{% endif %}

It seems to me that this results in the View being executed twice. Is there a better way to do this? I tried checking if drupal_view() returned empty, but even when the View is empty, it contains empty HTML elements.

💬 Support request
Status

Active

Version

3.4

Component

Code

Created by

🇨🇦Canada Liam Morland Ontario, CA 🇨🇦

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @Liam Morland
  • 🇷🇺Russia Chi

    but even when the View is empty, it contains empty HTML elements

    That's a known issue in Drupal theming system.

  • 🇨🇦Canada Liam Morland Ontario, CA 🇨🇦

    So, is my code snippet the recommended way to do it?

    To save rending the View twice, I thought that something like this would be possible:

    {% set view_content = drupal_view_result('related', 'block_1') %}
    {% if view_content is not empty %}
      <section>
        {{ view_content }}
      </section>
    {% endif %}
    
  • 🇷🇺Russia Chi

    It looks good. If the problem is only about rendering empty HTML markup you can also consider using CSS has selector to hide it.

  • 🇨🇦Canada Liam Morland Ontario, CA 🇨🇦

    Thanks. I would rather it not be on the page at all.

    I'd like to switch this to a feature request: Add a function which returns a printable value if there are results in the View and otherwise returns NULL. That would allow the new function to be used in place of drupal_view_result() in code like in #3.

  • 🇨🇦Canada Liam Morland Ontario, CA 🇨🇦
  • 🇷🇺Russia Chi

    Actually #3 is wrong. The snippet in issue summary looks correct.
    As of feature request I don't think it worth implementing. It looks more clear when checking for emptiness expensively. Function like drupal_view_if_not_empty() would look wierd.

  • 🇨🇦Canada Liam Morland Ontario, CA 🇨🇦

    I know the code in #3 would not work. I wrote that as an example of what I would like to be able to do in order to avoid executing the View twice.

    I think being more efficient is more important than not looking weird.

Production build 0.71.5 2024