2015-07-03 20 views
3

我在我的index.html中爲Jekyll獲得了以下代碼。我試圖找到一種方法將與每篇文章相關的類別鏈接到實際文章本身。所以,如果一個帖子包含「旅行」類別,我想點擊一個鏈接,指出「旅行」,這會將我帶到所有被歸類的帖子。如何鏈接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> 

回答

3

想通了。對於其他人想知道如何做同樣的事情,首先在你的根目錄下設置一個categories.html頁面。此頁面將列出符合特定類別的所有帖子。它通過將類別名稱轉換爲命名的錨節點,例如<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; 
} 

希望這有助於!

+0

那是'除非p.categories == empty'正確嗎?什麼是'p'?它看起來不對,但我不太瞭解這種語言,所以我只問。 – pgr

+0

一個可能的改進是使用過濾器'slugify'來創建錨點,將'多個單詞類別'變成'多個單詞類別'。 – pgr

相關問題