如何在Jekyll中链接文章分类

3
我在Jekyll的index.html中有以下代码。 我试图找到一种将与每篇文章相关联的类别链接到实际帖子本身的方法。 所以,如果一篇文章包含"travel"类别,我想单击一个名为"travel"的链接,它会将我带到所有分类为这样的帖子。
 <ul class="post-list" style="list-style-type: none;">
 {% for post in paginator.posts %}
    {% unless post.categories contains 'portfolio' %}
    <li>
    <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
    <span class="post-meta">{{ post.date | date: "%c" }}</span> &nbsp;
    Filed In: 
    {% unless p.categories == empty %}
                    {% for categories in post.categories %}
                        <a href="/{{ categories | first }}">{{ categories }}</a> //problem area
                    {% endfor %}
                {% endunless %}
    &nbsp;
    {{ post.excerpt }} <a href="{{ post.url }}">Find out more...</a><br><br>    
    </li> 
    {% endunless %}
   {% endfor %}
</ul>
1个回答

3
发现了解决方法。对于其他想要实现同样效果的人,首先要在根目录下设置一个名为categories.html的页面。该页面将列出符合特定类别的所有帖子。它通过将类别名称转换为命名锚点"slug"来完成此操作,例如<a href="#{{ category | first | remove:' ' }}",然后前面的代码创建了显示与该类别相关联的帖子的实际命名锚点div。最后,在您想要显示类别列表的页面或部分下,您需要呈现链接到categories.html页面中命名锚点部分的最终代码。
放入Categories.html的第一段代码:
<h2>Posts by Category</h2>
<ul>
 {% for category in site.categories %}
<li><a href="#{{ category | first | remove:' ' }}"><strong>{{ category | first }}</strong></a></li>
{% if forloop.last %}
    {% else %}  
    {% endif %}
    {% endfor %}
</ul>

放入Categories.html的第二段代码:

{% for category in site.categories %}
<div class="catbloc" id="{{ category | first | remove:' ' }}">
 <h2>{{ category | first }}</h2>
<ul>
{% for posts in category %}
{% for post in posts %}
{% if post.url %}
 <li>
  <a href="{{ post.url }}">
 <time>{{ post.date | date: "%B %d, %Y" }}</time> - 
{{ post.title }}
</a>
</li>
{% endif %}
{% endfor %}
{% endfor %}
</ul>
  </div>
   {% endfor %}

第三段代码是用于在您想要显示已命名的锚点链接类别的位置:

 Filed In: 
 {% unless p.categories == empty %}
 {% for categories in post.categories %}
 <a href="http://localhost:4000/category.html#{{categories}}">{{ categories }}</a>
 {% endfor %}
 {% endunless %}

使用以下CSS可以防止在点击之前部分内容提前显示:
.catbloc:not(:target){
 display: none;
}

希望这有所帮助!

“unless p.categories == empty” 这个语句正确吗?这里的“p”是什么意思?我感觉不对,但我并不熟悉这种编程语言,所以想请教一下。 - pgr
一个可能的改进是使用过滤器slugify来创建锚点,将A multi word category转换为a-multi-word-category - pgr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接