32

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
tipsywacky
  • 3,374
  • 5
  • 43
  • 75

3 Answers3

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

i Solve it with that way!!

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
buoge
  • 409
  • 5
  • 6
22

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 19
    For quick reference: {% if alist|length == 0 %} – edumike Oct 03 '17 at 21:28
  • 18
    -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 ;) – Henning Sep 05 '19 at 19:51
  • 5
    Since when was 'RTFM' considered an acceptable or helpful answer? – Will Jenkins Oct 22 '20 at 17:46
1
{% if alist.count() == 0 %}

That should solve your problem.

You can check out this link.

Community
  • 1
  • 1