0

在我的 Django 模板中,我经常调用它:

{% for name, address in directory.addressbook.items %}
  {% for street in address.list %}
    {{street.number}}

如何将其创建为过滤器?我试过这个,但它不起作用。

在模板中,我调用:

{{directory.addressbook.items|all_numbers}}

在我的过滤器定义中,我有:

def all_numbers(data):
  number_list=[]
  if isinstance(data, dict):
    for name, address in data:
      for street in data.list():
        number_list.append(street)
    return number_list

但我得到的只是“[]”。我究竟做错了什么?

4

1 回答 1

1

您需要将您的函数注册为模板过滤器。此外,此代码需要在一个模块中,然后导入到您的模板中......

# custom_filters.py
from django import template

register = template.Library()


@register.filter
def all_numbers(data):
  number_list=[]
  if isinstance(data, dict):
    for name, address in data:
      for street in data.list():  # this will raise an exception
        number_list.append(street)
    return number_list

# your-template.html
{% load custom_filters %}

{{ directory.addressbook.items|all_numbers }}
于 2013-06-06T00:48:44.850 回答