Hi,

not sure if this should be a bug report but let's start with a support request :)

Currently, we have to use the following code for conditionals based fields:

{% if content.field_more_infos['#items'] is not empty %}
  <div class="my-field-wrapper">
    {{ content.field_more_infos }}
  </div>
{% endif %}

would be much nicer if this worked intuitively:

{% if content.field_more_infos %}
  <div class="my-field-wrapper">
    {{ content.field_more_infos }}
  </div>
{% endif %}

Comments

dasjo created an issue. See original summary.

dasjo’s picture

When we figure out the proper way to handle this, let's add it to the docs:
https://www.drupal.org/node/1918824

Cottser’s picture

joelpittet’s picture

Status: Active » Closed (duplicate)

I think @Cottser is correct.

Try this.

{% if content.field_more_infos|render %}
  
{{ content.field_more_infos }}
{% endif %}

Or

{% set more_infos =  content.field_more_infos|render %}
{% if more_infos %}
  
{{ more_infos }}
{% endif %}
joelpittet’s picture

Also there is no really good way to deal with this problem at the moment in Twig or PHP template because it's hard to know what makes a render array truely empty and performance implications. Please continue the discussion in that issue referenced in #3

jwilson3’s picture

I'm finding that |render is not enough due to random whitespace issues from field templates, but the following works:

{% if content.field_more_infos|render|trim is not empty %}
  
    {{ content.field_more_infos }}
  
{% endif %}

the "is not empty" part may not be necessary, but |render|trim is absolutely needed.

Chi’s picture

@jwilson3 here is the trick for views. I suppose it works for fields as well.
https://www.drupal.org/node/2783633#comment-11510195

hkirsman’s picture

Tx, works for me at the moment in ds-2col-stacked.html.twig:

{%  if left|render|trim %}
    <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
      {{ left }}
    </{{ left_wrapper }}>
  {% endif %}
autopoietic’s picture

In case it helps someone else, I found that {% if content.field_myfield|render|trim is not empty %} does not work as expected if twig debug is enabled, because template suggestions are still returned when the field is otherwise empty.