1

I want to display on my node the number of comment and flag.

What should I add to my TWIG to get this?

How to count the number of comment and flag in a node?

Here is an example :

enter image description here

1 Answer 1

4

For the comment count you can get it in the node twig by:

{{ content.comment['#items'].comment_count }}

But the flag count i think there is no way to get it directly in the twig:
There is extension called flagcount in the flag module but it requires the flag object which is not available in node twig.
From comment section of flagcount callback function in flag/src/TwigExtension/FlagCount.php

/**
   * Gets the number of flaggings for the given flag and flaggable.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param \Drupal\Core\Entity\EntityInterface $flaggable
   *   The flaggable entity.
   *
   * @return string
   *   The number of times the flaggings for the given parameters.
   */

So the only way is to pass by preprocess like the following:

/**
 * Implements hook__preprocess_HOOK().
 */
function YOURMODULE_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  // Set your flag id here.
  $flag_id = 'bookmark';
  $variables['flag_count'] = \Drupal::service('flag.count')->getEntityFlagCounts($node)[$flag_id];
}

And then in you twig you can do:

{{ flag_count }}
4
  • 1
    Not sure, but you probably have to care about caching for the flag. Otherwise it won't increment unless you clear the cache. Maybe add the flag as #markup or #inline_template and let if have cache tagged with the nid and the flag id?
    – leymannx
    Dec 22, 2019 at 8:33
  • I managed to get the number of comments for a node with this code {{ node.field_article_commentaire.comment_count }} but it does not work with products. I tested this code and it returns nothing {{ product.field_produit_avis.comment_count }}
    – a713f93eb1
    Dec 22, 2019 at 18:37
  • Did you check that the comment field in product is field_produit_avis ?
    – berramou
    Dec 22, 2019 at 18:40
  • @berramou Yes it is the machine name of the field field_produit_avis
    – a713f93eb1
    Dec 23, 2019 at 11:01

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.