簡體   English   中英

在 Liquid 標簽中使用過濾器

[英]Using filters in Liquid tags

我正在使用 jekyll 和 Liquid 在 github 頁面上生成一個靜態網站。

我想根據文檔中的內容量是否達到特定作品數量來做出一些內容決策。 jekyll 有一個液體過濾器,它計算我想在 if 標簽中使用的單詞數。 我試過這個:

{% if page.content | number_of_words > 200 %} 
    ...
{% endif %} 

但它似乎不起作用。 我還嘗試將結果分配給一個變量並使用它,並捕獲過濾器的輸出。 但到目前為止,我沒有運氣。

有沒有人設法在液體標簽中使用過濾器?

{% assign val = page.content | number_of_words %}
{% if val > 200 %}
 ....
{% endif %}

編輯:這不再是最新的解決方案,請參閱並支持Martin Wang 的基於assign的解決方案

 {% assign val = page.content | number_of_words %} {% if val > 200 %} .... {% endif %} >```

在最初編寫此答案時(2011 年), assign不是可行的解決方案,因為它不適用於過濾器。 該功能於一年后,即2012 年推出

如果有人需要在舊版本的 Liquid 中處理這個問題,請在下面留下我 2011 年的原始答案。


我認為不可能以這種方式在標簽內使用過濾器; 這似乎不可能。

但是,我設法建立了一組可能解決您的特定問題的條件(辨別頁面是長於還是短於 200 個字)。 就是這個:

{% capture truncated_content %}{{ page.content | truncatewords: 200, '' }}{% endcapture %}

{% if page.content != truncated_content %}
  More than 200 words
{% else %}
  Less or equal to 200 words
{% endif %}

為了使計算更精確,使用strip_html運算符可能是明智的。 這給了我們:

{% capture text %}{{ page.content | strip_html }}{% endcapture %}
{% capture truncated_text %}{{ text | truncatewords: 200, '' }}{% endcapture %}

{% if text != truncated_text %}
  More than 200 words
{% else %}
  Less or equal to 200 words
{% endif %}

問候!

剛剛找到https://github.com/mojombo/jekyll/wiki/Plugins ,它提供了有關如何為 Github 編寫自定義標簽的詳細信息。 這看起來是一個可能的方向,並提供對其他開發人員的許多其他定制的訪問。

{% capture number_of_words_in_page %}{{page.content | number_of_words}}{% endcapture %}
{% if number_of_words_in_page > 200 %} 
    ...
{% endif %} 

嘗試這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM