【问题标题】:How to check a List for a match in Django?如何在 Django 中检查列表以查找匹配项?
【发布时间】:2011-01-10 03:50:00
【问题描述】:

假设:

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

我想:

{% if str is in strings %}

在 Django 中似乎不允许这样做。如果不是,检查列表中值的正确语法或方法是什么?

【问题讨论】:

  • 如何为这个问题添加赏金?

标签: python django list if-statement


【解决方案1】:

这是一个在 Google App Engine 上运行的应用。这是一个可以解决问题的自定义过滤器:

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)

【讨论】:

  • 当我在模板中检查传入的空值并在方法上方使用“@register.filter”时,这对我有用。我不需要最后两行
【解决方案2】:

程序员不喜欢多余的单词。试试:

{% if str in strings %}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 2020-02-13
  • 2012-11-07
  • 1970-01-01
相关资源
最近更新 更多