简体   繁体   中英

How do I get related posts in Jekyll to work?

I wanted to modify the answer found here but it doesn't seem to be working for me as it just results in duplicate statements of "there are no related posts".

Originally, when there are no related posts, nothing is displayed and I wanted to change that. Again, at the moment, with the else statement I added, it just displays "there are no related posts" 3 times and I cant seem to figure out why.

Any help would be appreciated.

{% 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 %}

In the linked answer there is no else block and no out put, it just generates 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 %}

Then it outputs a link as h5 in case sameTagCount is greater or equal minCommonTags.

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

In your case ìt outputs 'There are no related posts.' if the condition {% if page.tags contains tag %} is not true, which apparently happens three times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM