繁体   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