Great module. I use {{ drupal_view('view_name', 'view_display', arguments) }}
But I want to check first if view is not empty, and then display the result. How to do it?

CommentFileSizeAuthor
#5 how_to_check_if_view-2783633-5.patch1.27 KBsgurlt

Comments

AniaMi created an issue. See original summary.

chi’s picture

That is not possible with this approach. If you need to create some wrapper around the view I would suggest move it to view template.

chi’s picture

Component: Code » Documentation
Assigned: AniaMi » Unassigned
Category: Feature request » Support request
Status: Active » Fixed

Well, there is a trick. If a view returns nothing ("empty result behavior" is not configured).

{% set view = drupal_view('view_name')|render  %}
{%  if view|striptags|trim %}
  <div class="wrapper">
    {{ view }}
  </div>
{% endif %}

striptags and trim filters are needed in case the view returns empty markup with no content.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

sgurlt’s picture

Status: Closed (fixed) » Needs review
StatusFileSize
new1.27 KB

I had the same issue and sometimes the suggested solution did not work for me.
So I made myself some thoughts and created a patch for this.

With this patch applied, empty views are never getting printed out. The twig syntax has not changed, so we still can print out views with this:

{{ drupal_view('myView', 'myDisplay') }}

Additional it is now possible to do stuff like this:

{% set view_myView = drupal_view('myView', 'myDisplay') %}
  {% if view_myView %}
    <div class="misc">
      {{ view_myView }}
    </div>
  {% endif %}

Cheers :)

chi’s picture

Some people would like to display "Empty result text" or "View attachment" when a view has no results. The patch #4 is not acceptable for them. Furthermore it breaks backward compatibility.
Closing this as the reporter was given an answer.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

sgurlt’s picture

Interesting way to deal with someone who just wanted to help...
As mentioned your way did not work always so I think the feature request is still open.
In case of just rejecting my patch, it would be better to extend it and improve the module.

chi’s picture

@sgurlt I appreciate any help but this patch is not acceptable for reasons explained in #6.

devkinetic’s picture

For anyone landing here from a search engine, the pattern has changed.

{% set view = drupal_view_result('related', 'block_1')|length %}
{% if view > 0 %}
  {{ drupal_view('related', 'block_1') }}
{% endif %}

https://git.drupalcode.org/project/twig_tweak/-/blob/3.x/docs/views.md#c...