Using 'where' with custom data collection and int values

I have a file with the comments of my blog imported (originally from WP but transformed) in a data file named comments.toml. The structure goes like this:

id = 1
postId = 2
author = "Three"
url = "http://fo.ur"
date = 2006-05-04T03:02:01Z
content = """
my cool comment"""


In each post’s front matter there’s a field called id to be matched with the comment postId.

I wanted to show how many comments are there in a post, so my first attempt was:

$postId :=
$count := len (where .Site.Data.comments.comment "postId" $postId)

But $count is always zero. Then I tried the same code but instead of filtering by postId I used the field author:

$count := len (where .Site.Data.comments.comment "author" "existing_author")

And in this case works, so it seems quite strange to me. Am I doing something wrong?


PS: I solved it by filtering the range with an if and then using Scratch to keep the count of the matching items. Ugly but works.

Please post full solution :slight_smile:

As requested, I’ll add my solution. It’s absolutely suboptimal and it should be a one liner with where if it worked as I expected with integer values.

{{ $postId := }}
{{ $.Scratch.Set "ccount" 0 }}

{{ range $idx, $comment := .Site.Data.comments.comment }}
{{ if eq $comment.postId $postId }}
    {{ $curr := $.Scratch.Get "ccount" }}
    {{ $.Scratch.Set "ccount" (add $curr 1) }}   
{{ end }}
{{ end }}

{{ $commentCount := $.Scratch.Get "ccount" }}
1 Like