首页 > 解决方案 > 如何让 Jekyll 中的相关帖子正常工作?

问题描述

我想修改在这里找到的答案,但它似乎对我不起作用,因为它只会导致“没有相关帖子”的重复声明。

最初,当没有相关帖子时,什么都不会显示,我想改变它。同样,目前,使用我添加的 else 语句,它只显示“没有相关帖子”3 次,我似乎无法弄清楚原因。

任何帮助,将不胜感激。

{% assign maxRelated = 0 %}

{% assign minCommonTags =  3 %}

{% assign maxRelatedCounter = 0 %}

{% for post in site.posts %}

    {% assign sameTagCount = 0 %}
    {% assign commonTags = '' %}

    {% for tag in post.tags limit:1 %}

    {% if post.url != page.url %}
        {% if page.tags contains tag %}
        {% assign sameTagCount = sameTagCount | plus: 1 %}
        <a href="..{{ post.url | relative_url }}">{{ post.title }}</a>
        <p>{{ post.excerpt | strip_html | truncatewords:80 }}</p>
        {% assign commonTags = commonTags | append: tagmarkup %}
        {% else %}
        There are no related posts.
        {% endif %}

    {% endif %}
    {% endfor %}

    {% if sameTagCount >= minCommonTags %}

    {% assign maxRelatedCounter = maxRelatedCounter | plus: 1 %}
    {% if maxRelatedCounter >= maxRelated %}
        {% break %}
    {% endif %}
    {% endif %}

{% endfor %}

标签: jekyllliquid

解决方案


在链接的答案中没有其他块也没有输出,它只是生成 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 %}

然后它输出一个链接为 h5,以防 sameTagCount 大于或等于 minCommonTags。

{% if sameTagCount >= minCommonTags %}
   <div>
     <h5><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}{{ commonTags }}</a></h5>
   </div>
...

在您的情况下,“t 输出“没有相关帖子。” 如果条件{% if page.tags contains tag %}不成立,这显然会发生 3 次。


推荐阅读