In freemarker, how do I iterate over all blog posts with a particular tag, for example the tag "algorithms"?
<#assign relatedBlogs = ...>
<#if relatedBlogs?size > 0>
<h2>Related blog posts</h2>
<ul>
<#list relatedBlogs as blog>
<li>
<a href="${content.rootpath}${blog.uri}">${blog.title}</a>
</li>
</#list>
</ul>
</#if>
This doesn't work for me:
<#assign relatedBlogs = tagged_posts["algorithms"]>
This doesn't work either:
<#assign relatedBlogs = tags["algorithms"].tagged_posts>
tags
is a sequence, and to use tags[...]
you need a hash.
I ended up getting it to work through ?filter()
and ?first
:
<#assign relatedTags = tags?filter(tag -> tag.name == "algorithms")>
<#if relatedTags?size > 0>
<#assign relatedTag = relatedTags?first>
<h2>Algorithms related blog posts</h2>
<ul>
<#list relatedTag.tagged_posts as blog>
<li>
<a href="${content.rootpath}${blog.uri}">${blog.title}</a>
</li>
</#list>
</ul>
</#if>
This won't scale well, because filter()
iterates the tags for every page, but it works fast enough for websites with hundreds of pages. Here's the related issue.