AnswerBun.com

How to access a list's length in a template's code block for Django?

Stack Overflow Asked by Đỗ Nguyên Tùng on December 24, 2020

In a template, I have a variable of type list called "participants". I want to check if the length of the list is equal to 2, for example. I tried the following:

{{ participants | json_script:"participants"}}

{% if participants|length==2 %}

.....
{% endif %}

However, this does not work. The error I get is:

TemplateSyntaxError at /chat/lobby/
Could not parse the remainder: ‘==2’ from ‘participants.count==2’

Can someone point out a way to access a list’s length in a template’s code block? thank you for your time and consideration!

One Answer

The problem is the (lack of) spacing around the == part. If you rewrite this to

{% if participants|length == 2 %}
…
{% endif %}

the template parser will no longer error.

That being said, a template is used for rendering logic, and while it is hard to tell, it looks that this is more business logic, which, as @MeL says belongs in the views.

Correct answer by Willem Van Onsem on December 24, 2020

Add your own answers!

Related Questions

onMessageReceived() not being called | Discord Bot

1  Asked on February 7, 2021 by l0raxeo-c

     

Providing tabulated data to a SQL Update

0  Asked on February 7, 2021 by greg-b-roberts

     

Use list item index as index to another list in python

2  Asked on February 7, 2021 by jonna_983

     

how to create a persistence arraylist structure in java?

2  Asked on February 7, 2021 by pikachu-sir

   

IndexError: tuple index out of range when running python 3.9.1

1  Asked on February 7, 2021 by ahmad-nur-hasybi

       

Azure Functions in VS Code

2  Asked on February 7, 2021 by nje

     

Python __hash__ performance for bulky data

0  Asked on February 7, 2021 by user14848693

   

error: failed to push some refs to ‘https://github.com/

8  Asked on February 7, 2021 by koeradoera

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP