2016-08-25 122 views
0

我正在尋找在jekyll生成的網站上顯示來自csv文件的信息。我需要在csv文件中搜索適當的類別,然後在頁面上顯示其中的四個。過濾到選定的類別沒有問題,但我很難將輸出限制爲四個。在液體中顯示數據

有沒有辦法對if語句應用限制?或者有沒有其他的方式來寫這個?在Liquid中我不是那麼瞭解,所以很可能我錯過了一個明顯的解決方案。

Basic代碼,使所有適用的數據顯示在屏幕上:

 {% for study in site.data.studies %} 
     {% if study.category contains "foo" %} 
      <div class="col-sm-3"> 

       <h3>{{ study.title }}</h3> 
       <div class="list-of-attributes"> 

       <h6>Attributes: </h6> 
       {{ study.attributes }} 
       </div> 
      </div> 
     {% else %}  
      {% continue %} 
     {% endif %} 

     {% endfor %} 

我也試過unlesstablerow,無論其在所有工作。我至少在正確的軌道上?我怎樣才能限制這個循環以停止四個項目?

謝謝!

回答

1

理想的數據應該然而渲染之前被過濾,你還可以創建一個variable in liquid持有的東西數量呈現

{% assign rendered = 0 %} 

{% for study in site.data.studies %} 
    {% if study.category contains "foo" %} 
     <div class="col-sm-3"> 
     <h3>{{ study.title }}</h3> 
     <div class="list-of-attributes"> 

      <h6>attributes: </h6> 
      {{ study.attributes }} 
     </div> 
     </div> 

    {% assign rendered = rendered | plus: 1 %} 
    {% if rendered == 4 %} 
     {% break %} 
    {% endif %} 

    {% endif %} 
{% endfor %} 

理想的解決方案,我說的是創建自己的過濾器,做所有的工作(按類別過濾器並限制結果數)

{% assign filtered = site.data.studies | my_custom_filter %} 
{% for study in filtered %} 
    <div class="col-sm-3"> 
    <h3>{{ study.title }}</h3> 
    <div class="list-of-attributes"> 
     <h6>attributes: </h6> 
     {{ study.attributes }} 
    </div> 
    </div> 
{% endfor %} 
+1

我想'{%分配渲染=渲染|加上:1%}'比'{%assign rendered = rendered + 1%}'好,這是行不通的。 –

+0

感謝您的建議@DavidJacquel! –

+0

這太棒了,謝謝!我一直在嘗試類似的東西,但沒有得到它 - 現在我看到了你的解決方案,我明白我做錯了什麼。多謝! – avp

0

。假定你的category是一個字符串,而不是一個數組,你可以這樣做:

{% assign selected = site.data.studies | where: 'category','foo' %} 
{% for study in selected limit:4 %} 
    <div class="col-sm-3"> 
    <h3>{{ study.title }}</h3> 
    <div class="list-of-attributes"> 
     <h6>Attributes: </h6> 
     {{ study.attributes }} 
    </div> 
    </div> 
{% endfor %} 

如果你的category就像"foo, bar, baz"或與字符串數組字符串可以使用哲基爾3.2 where_exp過濾器是這樣的:

{% assign selected = site.data.studies | where_exp:"item", "item.category contains 'foo'" %} 
+0

對不起,我應該澄清一下:數據文件的類別包含多個字符串,因此它可能會讀爲「foo,bar,unicorn」 - 或者它可能會讀取「bar,unicorn,foo」。所以我需要使用'contains'而不是設置一個變量,然後從中取出。但是謝謝你! – avp