通过使用带有以下Liquid模板的 site.related_posts
,我已在我的网站中成功实现了 related posts :
下面的代码在每个帖子页面上返回4个与标签相关的帖子,到目前为止一直很好,但是为Jekyll集合实现这样的事情的最佳方法是什么?
{% assign hasSimilar = '' %}
{% for post in site.related_posts %}
{% assign postHasSimilar = false %}
{% for tag in post.tags %}
{% for thisTag in page.tags %}
{% if postHasSimilar == false and hasSimilar.size < 4 and post != page and tag == thisTag %}
{% if hasSimilar.size == 0 %}
{% endif %}
<a href="{{ site.baseurl }}{{ post.url }}" class="entry">
<div class="entry-media">
<img src="{{ post.thumbnail | prepend: site.baseurl }}" alt="">
<p class="post-cat">{% for category in post.categories.last %}{{ category }}{% endfor %}</p>
</div>
<h6 class="entry-title">{{ post.title | truncatewords: 70, '...' }}</h6>
<p class="post-date">{{ post.date | date: "%d/%m/%Y" }}</p>{% if post.series %}(Series: {{ post.series }}){% endif %}
</a>
{% capture hasSimilar %}{{ hasSimilar }}*{% endcapture %}
{% assign postHasSimilar = true %}{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
{% if hasSimilar.size > 0 %}
{% endif %}
根据Jekyll的文档,当你创建一个集合时,它可以通过 site
Liquid变量获得,就像 site.pages
和 site.posts
一样,所以为了为我的 portfolio 集合创建一个 related collection items ,我复制了上面的Liquid逻辑并将 site.portfolio 指定为帖子,请参阅:
{% assign posts = site.portfolio | sort: "tags" %}
因此,我在 _portfolio
集合中的每个"project.md"文档的前端设置了 tags: [tag1, tag2, tag3]
,因为我通常使用帖子,上面的流体逻辑返回相关的 portfolio collection items .
无论如何,虽然我'm not sure if this is the right path to achieve such functionality, it works as intended. I couldn'找到了 site.related_posts
的任何参考/用法 .
我真的很感激有关这个问题的任何想法 . 提前致谢 .
1 回答
site.related_posts
是ten most recent posts .所以,你的代码只在十个帖子中查找相关信息而不是所有帖子 .
以下代码将查找site.posts或任何site.collection的标签相关项