2

The version dev of the module "Flag" for "Drupal 8" has added a new sub module "Flag Count":

https://www.drupal.org/project/flag/issues/2708291

I copied the code

{% set count = '[' ~ flagcount(flag, flaggable) ~ ']' %}

in flag.html.twig and I copy this file into the templates folder of my theme (I did not cache it).

But after I do not know how to do it. Currently to display the flag link in node.html.twig I put the following code :

{{ content.flag_like_node }}

How to add the number of flag ?

I tested the following code and none works

{{ content.flag_like_node_count }}
{{ content.flag_like_node.count }}
{{ count }}

3 Answers 3

2

This will return an array of all the flag counts on a node:

\Drupal::service('flag.count')->getEntityFlagCounts($node)

(For all flags set for that node) Via: https://www.drupal.org/node/2476349

You can use that in a preprocess function to get your flag counts and send it as a new variable to your template file. Like so:

function yourtheme_preprocess_node(&$variables) {

  $flag_counts = \Drupal::service('flag.count')->getEntityFlagCounts($node);
  $variables['like_count'] = $flag_counts['like'];

}

Then in your theme file you can output:

{{ like_count }} 

The problem with this is that it doesn't ajax update when someone clicks the flag link. For that to work you have to put the count in the flag template.

2

For flag count to make it work in AJAX workflow:

  1. Use Dev version of Flag which has the flagcount function exposed to twig template.
  2. In flag.html.twig Add: {% set count = flagcount(flag, flaggable) %}
  3. use {{ count }} to display the counter.
0

I'm not sure when this moved out of dev, but in 8.x-4.0-beta4 here's how you do it:

  1. Copy flag.html.twig into wherever your theme's templates live

  2. Add {% set count = flagcount(flag, flaggable) %} to it somewhere. Best place is probably right before the line that starts with <div class="{{classes|join(' ')}}">

  3. Add {{ count }} after {{ title }} and span tag it, like this...

    <div class="{{classes|join(' ')}}"><a{{ attributes }}>{{ title }}<span>{{ count }}</span></a></div> 
    
  4. Flush caches

1
  • Worth noting: flag.html.twig will display the counter on every flag unless you put some logic in it to check for a particular flag. But the better method is to use template suggestions to rename flag.html.twig so it only applies to the appropriate flag. In my case, a comment with a flag called comment-upvote uses this template name: flag--comment-upvote.html.twig
    – aharown07
    Commented Feb 2, 2023 at 4:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.