0

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 %}
1

Okay, so It looks like this works:

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

Which looks incredibly stupid but well...

1

{% 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.

1
  • Though you do need to use |length if your title can literally be the string "0". See twig if docs for other twig bool edge cases.
    – sonfd
    Jul 21 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.