0

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. – 4k4 Aug 7 '18 at 20:51
0

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, privacy policy and cookie policy

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