Using filters in Liquid tags

随声附和 提交于 2020-05-10 06:57:47

问题


I'm using jekyll and Liquid to generate a static web site on github pages.

I want to base some content decisions on whether the amount of content in a document has reached a specific number of works. jekyll has a liquid filter which counts the number of words which I want to use in an if tag. I've tried this:

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

But it doesn't seem to work. I've also tried to assign the result to a variable and use that, and capture the output from the filter. But so far I've had no luck.

Has anyone managed to use a filter in a liquid tag?


回答1:


EDIT: This is no longer the most current solution, see and upvote Martin Wang's assign-based solution instead:

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

At the time this answer was originally written (2011) assign was not a viable solution since it did not work with filters. That feature was introduced one year later, in 2012.

Leaving my original 2011 answer below in case someone needs to deal with this problem in older versions of Liquid.


I don't think it's possible to use filters inside tags that way; it just doesn't seem possible.

However, I've managed to build a set of conditions that might solve your particular problem (discerning wether a page is longer or shorter than 200 words). This is it:

{% 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 %}

In order to make the calculations a little more precise, it might be wise to use the strip_html operator. That gives us:

{% 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 %}

Regards!




回答2:


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



回答3:


Just found https://github.com/mojombo/jekyll/wiki/Plugins which gives details on how to write a custom tag for Github. This looks like a possible direction to go as well as providing access to many other customisations from other developers.




回答4:


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

Try this.



来源:https://stackoverflow.com/questions/5972126/using-filters-in-liquid-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!