I have a view ("Tasks") that pulls in Task nodes, complete with sorting and filtering. Each Task can have multiple nodes attached via the "Related Articles" field (field_related_articles). I am trying to loop through each node (which can be a Video, Document, Article, etc.) and assign each link a class name depending on the type.

For example, a "Document" node attached to a Task would display a hyperlink with the document class. Video nodes will be video, and so on.

Here is my preprocess that is targeting the specific field:

function mytheme_preprocess_field__node__field_related_articles(&$variables) {
  $items = $variables['items'];

  foreach ($items as $index => $item) {
    $content_type = $item['content']['#options']['entity']->type->entity->label();
    $class_name = slugify($content_type); // custom function

    $variables['items'][$index]['attributes']['class'] = [$class_name];


When I inspect the $variables array, I see the following, which looks okay to me (but I can't be sure):

The items array inside $variables

As you can see, the attributes object now has a class value for each items value (I have two). However, in the HTML, the classes do not show up:

HTML output

Is there something I'm doing wrong?

  • Can you show the twig template? It looks like you've rendered the top level attributes twice instead of the item attributes.
    – 4uk4
    Commented Aug 7, 2018 at 20:51

1 Answer 1


So I finally figured out the problem.

I wasn't supposed to touch the $variables['items'][…]['attributes'] object, I was supposed to create a $variables['items'][…]['content']['#attributes'] array instead and put the class name(s) there.

Having done so, that now works.

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.