Using filters in Liquid tags

前端 未结 4 1329
广开言路
广开言路 2020-12-29 22:02

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

相关标签:
4条回答
  • 2020-12-29 22:07
    {% assign val = page.content | number_of_words %}
    {% if val > 200 %}
     ....
    {% endif %}
    
    0 讨论(0)
  • 2020-12-29 22:12

    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.

    0 讨论(0)
  • 2020-12-29 22:25

    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!

    0 讨论(0)
  • 2020-12-29 22:29
    {% capture number_of_words_in_page %}{{page.content | number_of_words}}{% endcapture %}
    {% if number_of_words_in_page > 200 %} 
        ...
    {% endif %} 
    

    Try this.

    0 讨论(0)
提交回复
热议问题