Skip to main content

Removing 'Add new comment' from teaser list

Submitted by ezybzy on

Since Drupal 8, I have been bugged with the behavior of Drupal teaser list, the list showing summary of nodes/blogs, which shows Add new comment link. There is no option to hide it by Drupal itself because it is an expected behavior of item link generation due to allowing annonymous comment. A few options are suggested such as

  • Using CSS to hide it
  • Modifying theme preprocessing/hooks to remove it

The CSS method isn't what I want because it cannot prevent BOT to traversing the link to comment form. So, I go for modifying theme mechanism and that takes me many months to figure this out!

Most of the answers are pointing to the bartik_preprocess_node(&$variables) which is implemented in many themes due to inheritance but somehow not working in this case. Finally, I found this document which explained how theme preprocessing/hook worked in Drupal. The preprocessing_links is the target. The hard part is this dependent with the availability of twig templates in your theme because it is the method name of the twig template!

For Bootstrap Barrio theme, there are

  • links.html.twig
  • theme suggestion links--inline.html.twig

to be used. I opt to use the theme suggestion one, links--inline.html.twig, to reduce its side effect. So, the method name will be {mytheme}_preprocessing_links__inline(&$variables). For the &$variables parameter, you can determine it from the content of the twig file itself or look at template_preprocess_links(). There is no way to determine whether this is used on teaser page or elsewhere. I solve this issue by determining for available of node-readmore link. Here is the final result of that.

/**
 * Implements hook_preprocess_HOOK() for links--inline.html.twig.
 */
//function {mytheme}_preprocess_links(&$variables) {}
function {mytheme}_preprocess_links__inline(&$variables) {

  // No way to determine 'teaser'
  if (isset($variables['links']['node-readmore'])) {
    unset($variables['links']['comment-add']);
  }
}

Hope you can modify this to fit your need.

Tags