2012-01-23 44 views
32

如果我在Liquid中使用了一個for循環(使用Jekyll),我怎樣才能定位偶數(或奇數)項目?我曾嘗試:液體模板:for循環中的偶數/奇數項

{% for item in site.posts %} 
    {% if forloop.index % 2 == 1 %} 

,但似乎並沒有工作。我也曾嘗試:

(forloop.index % 2) == 1 

和:

forloop.index - (forloop.index/2 * 2) == 1 

回答

52

我想你會想使用的循環標記這一點。例如:

{% for post in site.categories.articles %} 
    <article class="{% cycle 'odd', 'even' %}"></article> 
{% endfor %} 

如果你想爲每個週期不同的HTML標記:

{% for item in site.posts %} 
    {% capture thecycle %}{% cycle 'odd', 'even' %}{% endcapture %} 
    {% if thecycle == 'odd' %} 
    <div>echo something</div> 
    {% endif %} 
{% endfor %} 

你可以找到Liquid for Designers它的更多信息,雖然比如有沒有特別有幫助。這Shopify support thread也應該有所幫助。

+1

這不是正是我一直在尋找,但您發現鏈接讓我真正的答案。我編輯了你的答案以包含我的解決方案。謝謝! –

+0

另外,如果我只想使用CSS,你的解決方案將工作,但我想將'site.posts'分成兩列,所以只有類切換對我來說是不夠的。 –

+0

是的,我不確定你是否在尋找使用CSS或不。很高興幫助! –

10

相較於什麼Ales Lande's answerShopify support thread說,有將液體A modulo功能 - 在the modulo filter形式。

有了它,你可以這樣做:

{% for item in site.posts %} 
    {% assign mod = forloop.index | modulo: 2 %} 
    {% if mod == 0 %} 
     <!-- even --> 
    {% else %} 
     <!-- odd --> 
    {% endif %} 
{% endfor %} 
+1

我喜歡這個解決方案比使用'cycle'的解決方案更好;用字符串解決數學問題似乎...奇怪! –