1

I've put the following code above print render($content['comments']); in comment-wrapper.tpl.php of our theme to add question or answer class to every comment:

    foreach($content['comments'] as &$c) {
      if(is_array($c) && array_key_exists('#entity_type', $c) && $c['#entity_type'] == 'comment') {
        $uid = $c['comment_body']['#object']->uid;
        $c['#attributes']['class'][] = $uid == 1 ? 'answer' : 'question';
      }
    }

The generated HTML however has no question or answer classes. Please help me to correct the error.

1

The following code worked for me, put it in your theme's template.php and replace theme with the name of your theme:

function theme_preprocess_comment(&$vars) {
  $element = $vars['elements'];
  $comment = $element['#comment'];

  if(array_key_exists('#entity_type', $element) && $element['#entity_type'] == 'comment') {
    $vars['classes_array'][] = $comment->uid == 1 ? 'answer' : 'question';
  }
}

Although I think the extra checks for entity type is not necessary since this theme is only applied to comments.

1

I think your ternary statement is off in that code.

I would also suggest an alternative approach. You can use hook_preprocess_comment() in a template.php file or in a custom module. With this you can hook into the comment before it's rendered to the page, run each comment through an logic test and add a class to the entire comment, or add an html chunk before or after the comment's html. See more on hook_preprocess and render arrays.

  • 1
    I can't see anything wrong with that ternary statement, it translates to if ($uid == 1) { $c['#attributes']['class'][] = 'answer'; } else { $c['#attributes']['class'][] = 'question'; }. Could you expand on what you mean by that? – Clive Feb 20 '13 at 16:45
  • Okay fair enough. It looked off to me because I'm used to seeing parentheses around the first expression. – cdmo Feb 21 '13 at 1:49

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.