How to add variable using mytheme_preprocess_field and print using twig template? We have a content type Article that has two custom fields: field_header and field_link. When field_header is not populated, we want to perform validation in twig template to add a CSS class. When we tried to set a custom variable using $variables['myVariable'] = TRUE and try to print the value in the twig template, it is returning a NULL value. 

How can I create a custom variable using mytheme_preprocess_field() hook and use it in the twig template?

mytheme.theme

function mytheme_preprocess_field(&amp;$variables) {
  $element = $variables['element'];
  if($element['#field_name'] == 'field_header') {
    if($element['#items']-&gt;first()-&gt;isEmpty()) {
      $variables['myVariable'] = TRUE;
    }
  }
}


node--article.html.twig

&lt;div&gt;
  {{ kint(myVariable) }} // Returns NULL everytime.

  {% if myVariable %}
    // If not empty, do something.
  {% else %}
    // If empty, do something else. 
  {% endif %}
&lt;/div&gt;
Variables in a template are scoped - what you add in hook_preprocess_field will only be available in field.html.twig and its derivatives, not node.html.twig etc.

You can implement the same logic in the node preprocess:

function mytheme_preprocess_node(&amp;$variables) {
  if ($variables['node']-&gt;hasField('field_header') &amp;&amp; $variables['node']-&gt;field_header-&gt;isEmpty()) {
    $variables['myVariable'] = TRUE;
  }
}