Jekyll和liquid - 按相等标签数量显示相关帖子> = 2

Vin*_*ton 2 tags liquid jekyll

我想在每个帖子的底部添加一个名为"相关帖子"的栏,并且相关帖子的标准和出现应该是两个帖子中至少有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 %}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Dav*_*uel 13

这段代码可以解决问题:

<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>
Run Code Online (Sandbox Code Playgroud)

编辑:为maxRelated和添加'配置' minCommonTags,加上测试以避免将帖子放入自己相关的帖子列表中.