28

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

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

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

但这似乎不起作用。我还尝试将结果分配给一个变量并使用它,并从过滤器中捕获输出。但到目前为止,我还没有运气。

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

4

4 回答 4

29
{% assign val = page.content | number_of_words %}
{% if val > 200 %}
 ....
{% endif %}
于 2013-12-11T14:33:20.130 回答
21

编辑:这不再是最新的解决方案,请参阅并支持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 %}

问候!

于 2011-05-23T13:51:25.800 回答
1

刚刚发现https://github.com/mojombo/jekyll/wiki/Plugins提供了有关如何为 Github 编写自定义标签的详细信息。这看起来像是一个可能的方向,并提供对其他开发人员的许多其他定制的访问。

于 2011-05-23T03:21:25.887 回答
0
{% capture number_of_words_in_page %}{{page.content | number_of_words}}{% endcapture %}
{% if number_of_words_in_page > 200 %} 
    ...
{% endif %} 

试试这个。

于 2011-05-23T01:48:28.993 回答