【问题标题】:Jekyll and liquid - Show related posts by amount of equal tags >= 2Jekyll 和 Liquid - 按相等标签的数量显示相关帖子 >= 2
【发布时间】:2014-08-17 10:32:21
【问题描述】:

我想在每个帖子的底部添加一个名为“相关帖子”的栏,并且帖子相关和出现的标准应该是 至少有 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 %}

感谢您的帮助!

【问题讨论】:

标签: tags jekyll liquid


【解决方案1】:

这段代码可以解决问题:

<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>

编辑:为maxRelatedminCommonTags 添加了“配置”,以及避免将帖子放入自己相关帖子列表的测试。

【讨论】:

    猜你喜欢
    • 2012-04-21
    • 2015-03-24
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多