Score:0

Unable to check if variable is empty in views twig

in flag
Lub

I am trying to overwrite views-view-unformatted.html.twig file and want to check if title variable is empty or not, but whatever I do, it always acts just like it is not empty.

I know title variable is an object, I tried dpm() it but no modifiers work in checking if it is empty.

My code:

{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{{ dpm(title) }}
{% if title|render|trim|length is not empty %}

{% set row_id = 1 %}

{% for key, row in rows %}
    {% set row_id = key+1 %}
{% endfor %}
<a data-toggle="collapse" href="#collapse-{{ row_id }}" role="button" aria-expanded="false" aria-controls="collapse-{{ row_id }}">
  <h3>{{ title }}</h3>
</a>
<div class="collapse" id="collapse-{{ row_id }}">
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row views-row-' ~ loop.index
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}
{% if title|render|trim|length is not empty %}
</div>
{% endif %}
Smartsheet eng avatar
um flag
https://www.drupal.org/project/twig_capture is related.
Score:1
in flag

{% if title|render|striptags|trim %} should work.

  1. title|render to render, i.e. convert from render array to html string.
  2. |striptags to remove any html tags from the rendered title.
  3. |trim to remove any whitespace from beginning and end.

If title is already an html string (i.e. not a render array) then you can omit |render and {% if title|striptags|trim %} should be good enough.

sonfd avatar
in flag
Though you do need to use `|length` if your title can literally be the string "0". See [twig if docs](https://twig.symfony.com/doc/3.x/tags/if.html) for other twig bool edge cases.
Score:0
in flag
Lub

Okay, so It looks like this works:

{% if title|trim|spaceless|striptags|length != 0 %}

Which looks incredibly stupid but well...

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.