我想添加一个名为"相关帖子"在每个帖子的底部以及相关和要显示的帖子标准应该是两个帖子中最少2个相等标签的数量。
到目前为止我的方法:
{% for tag in page.tags %}
{% assign currentTag = tag | first %}
{% for post in site.posts | limit:3 %}
{% if post.tags contains currentTag | plus:1 %}
<div>
<a href="{{ post.url }}">
<img src="{{site.baseurl}}/asset/img/{{ post.img-thumb }}">
</a>
<h5> {{ post.title }}</h5>
</div>
{% endif %}
{% endfor %}
{% endfor %}
感谢您的帮助!
答案 0 :(得分:12)
这段代码可以解决问题:
<div class="relatedPosts">
<h3>Related post</h3>
{% comment %}---> the maximum number of related to posts
to be printed {% endcomment %}
{% assign maxRelated = 5 %}
{% comment %}---> the minimum number of common tags
to have for a post to be considered
as a related post {% endcomment %}
{% assign minCommonTags = 3 %}
{% assign maxRelatedCounter = 0 %}
{% for post in site.posts %}
{% assign sameTagCount = 0 %}
{% assign commonTags = '' %}
{% for tag in post.tags %}
{% comment %}---> Only compare if post is
not same as current page {% endcomment %}
{% if post.url != page.url %}
{% if page.tags contains tag %}
{% assign sameTagCount = sameTagCount | plus: 1 %}
{% capture tagmarkup %} <span class="label label-default">{{ tag }}</span> {% endcapture %}
{% assign commonTags = commonTags | append: tagmarkup %}
{% endif %}
{% endif %}
{% endfor %}
{% if sameTagCount >= minCommonTags %}
<div>
<h5><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}{{ commonTags }}</a></h5>
</div>
{% assign maxRelatedCounter = maxRelatedCounter | plus: 1 %}
{% if maxRelatedCounter >= maxRelated %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
</div>
修改:添加了&#39;配置&#39;对于maxRelated
和minCommonTags
,加上一个避免发帖的测试是自己相关的帖子列表。