How to check a list for compliance in Django?

Assuming that:

strings = ["abc", "a", "bc"]
str = "bc"

I want to:

{% if str is in strings %}

This doesn't seem to be allowed in Django. If this is not the correct syntax or method for checking the value in a list?

+3
source share
2 answers

This application is powered by Google App Engine. Here is a special filter that will do the trick:

from google.appengine.ext.webapp import template
from django import template as django_template

def in_list(value, arg):
  """
  Given an item and a list, check if the item is in the list.
  Usage:
  {% if item|in_list:list %} 
      in list 
  {% else %} 
      not in list
  {% endif %}
  """
  return value in arg

register = template.create_template_register()  
ifinlist = register.filter(in_list)
+4
source

Programmers don't like extra words. Try:

{% if str in strings %}
+1
source

Source: https://habr.com/ru/post/1784457/


All Articles