Lego2012
8/1/2017 - 12:52 PM

Get first three posts in a tag in a section

Get first three posts in a tag in a section

Okay, this is gross, but since intersect and in didn't work (string/interface array issues that are apparently known bugs), it's the best I could come up with. So, given an entry in config.toml like this (lower-case because taxonomy terms are normalized):

[params]
featured = ["cdn","hosting"]
{{ range where .Site.RegularPages "Section" "news" }}
  {{ $.Scratch.Set "tmp" 0 }}
  {{ range .Params.categories }}
    {{ if in $.Site.Params.featured . }}
       {{ $.Scratch.Add "tmp" 1 }}
    {{ end }}
  {{ end }}
  {{ if eq ($.Scratch.Get "tmp") (len $.Site.Params.featured) }}
    {{ $.Scratch.Add "match" (slice .) }}
  {{ end }}
{{ end }}

<ul>
{{ range first 2 ($.Scratch.Get "match") }}
  <li>{{ .Title }}</li>
{{ end }}
</ul>

Warning: it's slow, since it's looping over every article in the section. Not significant for smallish sites, but when I tested it on the paginated homepage of my large blog (2,850 articles, 357 pages), the build time went from 13 seconds to 43!). You only want to run this once per site, perhaps in a partialCached template.