Python jinja2 template, how to count a list

28,402

Solution 1

If you do a quick search in the template documentation you will quite soon find the length filter.

As for the rest, read the documentation.

Solution 2

{% if alist |length ==0 %}  or  {% if alist |count ==0 %}

i Solve it with that way!!

Solution 3

{% if alist.count() == 0 %}

That should solve your problem.

You can check out this link.

Share:
28,402

Related videos on Youtube

tipsywacky
Author by

tipsywacky

python for real...

Updated on March 31, 2020

Comments

  • tipsywacky
    tipsywacky about 4 years

    So I can't use python len() for a list in the templates like below.

    {% if len(alist) == 0 %}
    
    UndefinedError: 'len' is undefined
    
    1. How can we use python in the templates?

    2. Is passing a param to the template in the def get(self) method the only way to do this?

    3. Anyone know some good resources on how to use jinja2 with it comes to templating? like what methods can you use and the syntactic difference between python and jinja2.

  • tipsywacky
    tipsywacky over 11 years
    exactly what i'm looking for. thanks.
  • Lava Sangeetham
    Lava Sangeetham about 7 years
    i am getting following error TypeError: count() takes exactly one argument (0 given)
  • edumike
    edumike over 6 years
    For quick reference: {% if alist|length == 0 %}
  • Henning
    Henning over 4 years
    -1 cause you could have saved us your remark implying the person asking the question being too lazy to search the docs. Some things you dont find as easy if you don't know exactly what to search for. And IMHO it's the responsiblity of Jinja's authors to create a template language that looks like being "normal" python, but in certain corner cases isn't, and then throwing pretty unclear error messages. Thanks for the 1/4 helpful part of your answer ;)
  • Will Jenkins
    Will Jenkins over 3 years
    Since when was 'RTFM' considered an acceptable or helpful answer?
  • Amit Pathak
    Amit Pathak about 2 years
    count() counts a specific item. I don't think this works, please correct if required.