I want to range though blog posts and get a count of tags / images associated with each post

I have a “blog listing” /posts/ table I am creating. I have the title / date / location (custom front mater field) / I have also added a list of “tags” and a listing of images that are in the page bundle. What I would like is to just get a count of the tags and images to add to my table.

<table id="myTable">
    <thead><th>Blog Post</th><th>Date</th><th>Location</th><th>Images</th><th>Tags</th>
    </thead>
{{ range .Pages }}
<tr><td><a href="{{ .Permalink }}">{{ .Title }}</a></td>
    <td>{{  .Date.Format "2006-01-02"  }}</td>
    <td>{{ .Params.Location }}</td>
    <td> 
        {{ with .Resources.ByType "image" }}
        {{ range . }}
             {{ .Name }}<br />
        {{ end }}
        {{ end }}
    </td>
    <td>
        {{ range (.GetTerms "tags") }}
        {{ .Title }}<br />
           {{ end }}
    </td>
</tr>
{{ end }}
</table>

I am very new to hugo / go html templates. I have seen several good code snippets that start with the “tags” and count the posts for each of them but I am looking to go in the other direction.

You can do that by using len like this:

<table id="myTable">
    <thead><th>Blog Post</th><th>Date</th><th>Location</th><th>Images</th><th>Tags</th>
    </thead>
{{ range .Pages }}
<tr><td><a href="{{ .Permalink }}">{{ .Title }}</a></td>
    <td>{{  .Date.Format "2006-01-02"  }}</td>
    <td>{{ .Params.Location }}</td>
    <td> 
        {{ with .Resources.ByType "image" }}
        
        {{ len . }}
        
        {{ range . }}
             {{ .Name }}<br />
        {{ end }}
        {{ end }}
    </td>
    <td>
        {{ len (.GetTerms "tags") }}
        {{ range (.GetTerms "tags") }}
        {{ .Title }}<br />
           {{ end }}
    </td>
</tr>
{{ end }}
</table>
1 Like

Awesome. Thank you. I will have to read up on that.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.