【问题标题】:How to link post categories in Jekyll如何在 Jekyll 中链接帖子类别
【发布时间】:2015-07-03 23:43:20
【问题描述】:

我的 index.html 中有 Jekyll 的以下代码。我正在尝试找到一种方法将与每个帖子相关联的类别链接到实际帖子本身。因此,如果帖子包含“旅行”类别,我想单击一个显示“旅行”的链接,这会将我带到所有此类分类的帖子。

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

【问题讨论】:

    标签: jekyll jekyll-extensions


    【解决方案1】:

    想通了。对于其他想知道如何做同样的事情的人,首先在你的根目录中设置一个categories.html 页面。此页面将列出符合特定类别的所有帖子。它通过将类别名称转换为诸如&lt;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 是什么?对我来说它看起来不对,但我真的不知道这种语言,所以我只是问。
    • 一个可能的改进是使用过滤器slugify来创建锚点,将A multi word category变成a-multi-word-category
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2014-01-03
    • 2014-01-19
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多