0

I created two content type Writer & Book. Writer has entity reference field that link to Book nodes. When display Writer node, I like the book nodes that attached to it display as list and the first list item has CSS class of "first".

Output the list is simple but I couldn't figure out how to add that CSS class.

If possible, I prefer do it with template.php or node--content_type.tpl.php flies, not using JQuery, Views or another modules.

Appreciate any suggestions, Thanks!

1 Answer 1

0

Inside your tempalate.php file, add the following for that field. This is the standard implementation of theme_field. I added the line if ($delta == 1) $classes .= ' first'; to add the class.

function yourthemename_field__yourfieldname ($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables ['label_hidden']) {
    $output .= '<div class="field-label"' . $variables ['title_attributes'] . '>' . $variables ['label'] . ':&nbsp;</div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables ['content_attributes'] . '>';
  foreach ($variables ['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    //add your class here
    if ($delta == 1) $classes .= ' first';
    $output .= '<div class="' . $classes . '"' . $variables ['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables ['classes'] . '"' . $variables ['attributes'] . '>' . $output . '</div>';


  return $output;
}

Furthermore, you can change this for different view modes and different bundles. The rest is in documentation.

2
  • Thank you so much. It fixed my problem. I've been searching it for like a day and I know there is something I can do about the class just don't know where. Thanks again!
    – wzh
    Commented Jun 18, 2015 at 0:51
  • You welcome. :)
    – duru
    Commented Jun 18, 2015 at 14:38

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.