检查列表django模板中是否存在

时间:2022-10-16 19:22:14

I want to check if a value belongs to a list in django template. Something like this

我想检查一个值是否属于django模板中的列表。像这样的东西

{% if value in ['Pass','Fail'] %}

{%if in ['Pass','Fail']%}

How can I achieve this?

我怎样才能做到这一点?

3 个解决方案

#1


30  

I don't think that you can define a list directly in the template. You could pass a list to the template and do

我认为您不能直接在模板中定义列表。您可以将列表传递给模板并执行

{% if value in my_list %}

Alternatively, you could write a template tag which takes parameters like this:

或者,您可以编写一个模板标记,其中包含以下参数:

{% ifinlist value "val1,val2,val3" %}

#2


4  

Django Template:

Django模板:

{% value|ifinlist:"val1,val2,val3" %}

Template Tag:

模板标签:

from django import template

register = template.Library()

@register.filter(name='ifinlist')
def ifinlist(value, list):
    return True if value in list else False

#3


1  

You could write the if condition as

您可以将if条件写为

{% if value in 'Pass,Fail' %}

{%if'Pass,Fail'%}中的值

No need of template tag or list from backend

无需后端的模板标签或列表

#1


30  

I don't think that you can define a list directly in the template. You could pass a list to the template and do

我认为您不能直接在模板中定义列表。您可以将列表传递给模板并执行

{% if value in my_list %}

Alternatively, you could write a template tag which takes parameters like this:

或者,您可以编写一个模板标记,其中包含以下参数:

{% ifinlist value "val1,val2,val3" %}

#2


4  

Django Template:

Django模板:

{% value|ifinlist:"val1,val2,val3" %}

Template Tag:

模板标签:

from django import template

register = template.Library()

@register.filter(name='ifinlist')
def ifinlist(value, list):
    return True if value in list else False

#3


1  

You could write the if condition as

您可以将if条件写为

{% if value in 'Pass,Fail' %}

{%if'Pass,Fail'%}中的值

No need of template tag or list from backend

无需后端的模板标签或列表