代码之家  ›  专栏  ›  技术社区  ›  JamesRocky

如何让Jekyll中的相关帖子生效?

  •  0
  • JamesRocky  · 技术社区  · 4 年前

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

    最初,当没有相关帖子时,什么也不显示,我想改变这一点。同样,目前,我添加了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 %}
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Christian    4 年前

    在链接的答案中,没有其他块,也没有输出,它只生成commonTag。

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

    然后,如果sameTagCount大于或等于minCommonTags,它会输出一个链接h5。

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

    在你的例子中,t输出“没有相关帖子”如果条件 {% if page.tags contains tag %} 事实并非如此,这显然发生了三次。