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?


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


  {{ kint(myVariable) }} // Returns NULL everytime.

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

1 Answer 1


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(&$variables) {
  if ($variables['node']->hasField('field_header') && $variables['node']->field_header->isEmpty()) {
    $variables['myVariable'] = TRUE;
  • that highlighted my problem, can't believe i did not see. making the change solved the problem once i converted to hook_preprocess_node Jul 3, 2018 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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