0

During template_preprocess_node I would like to be able to dynamically add classes to specific field wrappers.

Is this possible or does template_preprocess_node run after template_preprocess_field? I would much prefer to use template_preprocess_node if possible as the class relies on other fields.

I've tried adding:

$vars['content']['field_name']['classes']
$vars['content']['field_name']['classes_array']

but neither seem to take effect.

Were I to do the same within template_preprocess_field then I apparently would add classes to $classes_array which would automatically flatten into $classes, however these values don't appear to be available, or at least provided, to template_preprocess_node?

EDIT:

After investigation, it seems template_preprocess_node does run first, however it doesn't seem to have access to $classes_array as it appears in template_preprocess_field.

1 Answer 1

3

Ok my somewhat dirty solution was to pass a classes array from template_preprocess_node to template_preprocess_field:

function template_preprocess_node(&$vars){
  if(!isset($vars['content']['field_name']['classes_array'])){                                                                                   
    $vars['content']['field_name']['classes_array'] = array();                                                                                   
  }                                                                                                                                                          
  $vars['content']['field_name']['classes_array'][] = 'custom-class';
}

function template_preprocess_field(&$vars){                                                                                                                    
  if(isset($vars['element']['classes_array'])){                                                                                                                    
    $vars['classes_array'] = array_merge($vars['classes_array'], $vars['element']['classes_array']);                                                               
  }                                                                                                                                                                
}

If there's a more 'official' way to do this, please feel free to enlighten me and I'll re-award the answer :)

Your Answer

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

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