How to add variable using mytheme_preprocess_field and print using twig template?

04/07/2018


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(&$variables) {
  $element = $variables['element'];
  if($element['#field_name'] == 'field_header') {
    if($element['#items']->first()->isEmpty()) {
      $variables['myVariable'] = TRUE;
    }
  }
}

node–article.html.twig

<div>
  {{ kint(myVariable) }} // Returns NULL everytime.

  {% if myVariable %}
    // If not empty, do something.
  {% else %}
    // If empty, do something else. 
  {% endif %}
</div>

قالب وردپرس