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 :
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityFor 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 }}
{{ 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 }}
Dec 22, 2019 at 18:37
field_produit_avis
?
field_produit_avis
Dec 23, 2019 at 11:01