在Liquid标签中使用过滤器

dre*_*kka 23 tags filter liquid jekyll

我正在使用jekyll和Liquid在github页面上生成一个静态网站.

我想根据文档中的内容量是否达到特定数量的作品来做出一些内容决定.jekyll有一个液体过滤器,用于计算我想在if标签中使用的单词数.我试过这个:

{% if page.content | number_of_words > 200 %} 
    ...
{% endif %} 
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.我还尝试将结果分配给变量并使用它,并捕获过滤器的输出.但到目前为止,我没有运气.

有人设法在液体标签中使用过滤器吗?

Mar*_*ang 26

{% assign val = page.content | number_of_words %}
{% if val > 200 %}
 ....
{% endif %}
Run Code Online (Sandbox Code Playgroud)

  • 似乎是唯一干净的方法.真的没有文件说明比较不能与过滤器结合使用吗? (3认同)

kik*_*ito 18

我认为不可能在标签中使用过滤器; 它似乎不可能.

但是,我已经设法构建了一组可以解决您的特定问题的条件(辨别页面长度或短于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 %}
Run Code Online (Sandbox Code Playgroud)

为了使计算更加精确,使用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 %}
Run Code Online (Sandbox Code Playgroud)

问候!