2016-08-16 72 views
0

我試圖解決這個問題,一直無法得出一個幸福的結論。如何使用Jekyll和Liquid根據帖子數量列出帖子?

基本上,我想要做的是檢測我的Jekyll站點上的帖子數量,並根據該數量列出帖子數量。例如,如果只有一個帖子,我想列出該帖子,全長和所有格式。如果有兩個帖子,我想將它們都列爲片段,並且沒有HTML格式。如果有三個,則與兩個帖子相同。如果有超過三個,我想要做兩個和三個帖子一樣的,但有一個「查看所有帖子」鏈接,因爲我想在主頁上列出三個最大值,但不希望「查看所有職位「鏈接,如果不超過三個職位。

在列出我的當前代碼之前,我想說明一下,我已經嘗試使用paginator.total_posts(我在我的網站上使用了jekyll-paginate),並且沒有列出任何內容。

這是我的時刻代碼:

{% if site.posts | size == 1 %} 
    {% for post in site.posts %} 
    {{ first post coding, full-length }}  
    {% endfor %} 
{% endif %} 
{% if site.posts | size == 2 %} 
    {% for post in site.posts limit:1 %} 
    {{ first post coding, snippet }}  
    {% endfor %} 
    {% for post in site.posts limit:1 offset:1 %} 
    {{ second post coding, snippet }} 
    {% endfor %} 
{% endif %} 
{% if site.posts | size == 3 %} 
    {% for post in site.posts limit:1 %} 
    {{ first post coding, snippet }}  
    {% endfor %} 
    {% for post in site.posts limit:1 offset:1 %} 
    {{ second post coding, snippet }} 
    {% endfor %} 
    {% for post in site.posts limit:1 offset:2 %} 
    {{ third post coding, snippet }}  
    {% endfor %} 
{% endif %} 
{% if site.posts | size > 3 %} 
    {% for post in site.posts limit:1 %} 
    {{ first post coding, snippet }}  
    {% endfor %} 
    {% for post in site.posts limit:1 offset:1 %} 
    {{ second post coding, snippet }} 
    {% endfor %} 
    {% for post in site.posts limit:1 offset:2 %} 
    {{ third post coding, snippet }}  
    {% endfor %} 
    {{ "view all posts" link coding }} 
{% endif %} 

問題是,我的網頁與所有{% if %}報表輸出;它不是隻選擇一個,即爲{{ site.posts | size }}輸出的數字。這使我感到困惑,因爲當我在我的代碼中放入{{ site.posts | size }}時,它會在每種情況下列出正確的編號。

我試過改變==contains甚至:,但我仍然得到相同的結果。

我不確定該從哪裏出發,所以任何幫助都非常感謝。提前致謝。

回答

1

您不應該混用測試和過濾器。請嘗試以下操作:

{% assign post_count=site.posts | size %} 
{% if post_count == 1 %} 
... 

注意使用數組,你可以使用,而不是一個過濾器的尺寸屬性:

{% if site.posts.size == 1 %} 
... 
+0

我試過'{%如果site.posts.size == 1%}'沒有成功,但你的其他建議完美。非常感謝! :) – chrisco97

+0

我可以發誓我在發佈問題之前嘗試過'{%if site.posts.size == 1%}',但我現在再試一次,它的工作原理與另一個選項完全相同。奇怪的。我道歉! :) – chrisco97

+0

回答之前我沒有測試自己,我應該這樣做:) – wasthishelpful