Post

Check if drupal field is empty with twig

Being new to drupal performing the simple conditional statement requires a bit of digging. My favorite php tool when dealing with something new is to grab an object and dump. I want to see whats in these things. Twig templating in drupal is made easier for all theme developers with the powerful {{dump(_context|keys)}}

See what variables are available to us

this will output a range of variables available to the template.

1
   {{ dump(_context|keys) }}

Now that we know what keys we can work with. Choose a variable from the output list to explore further

1
2
3
<pre>
   {{ dump(path) }}
</pre>

Check if user is on the homepage

I want to hide the title if the user is on the homepage

1
2
3
   {% if path is not same as '/node/2' %}
      {{ title }}
   {% endif %}

Conditional Loading of Bootstrap Attributes

Condtional logic based on what node is being viewed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{% if path is same as '/node/37' %}
{% set classes = ['tab-pane', 'fade', 'show', 'active'] %}
{% set content_id = 'trades' %}
{% set content_role = 'tabpanel' %}
{% set content_aria_label = 'trades' %}
{% endif %}

<article {{attributes.setAttribute('id', content_id).setAttribute('role', content_role).setAttribute('aria-labelledby', content_aria_label)}} {{ attributes.addClass(classes) }}>
  {% block content %}
    <div{{ content_attributes }}>
      {{ content }}
    </div>
  {% endblock %}
</article>

Get value from boolean and output Bootstrap class

Here we output a css class based on the value of the boolean field

1
2
3
4
5
6
7
8
9
10
11
12
13
{% set mybool = content.field_name.0['#markup']  %}
{% if mybool == 'On' %}
 {% set mybool = 'my_true_val' %}
 {% else %}
 {% set mybool = 'my_false_val' %}
{% endif %}
{%
  set classes = [
    'otherclass',
    'otherclass-1',
    mybool
  ]
%}

if field is empty don’t render it

Avoid rendering the content if the field is empty

  • only render if the field contains content
1
2
3
4
5
6
    {% if content.title | render %}
    <h4>
      {{ content.title }}
    </h4>
    {% endif %}

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.