Skip to main content
 首页 » 编程设计

python之为什么 Django 模板语言不允许像 [0][1] 这样的东西

2025年05月04日22qq号

当我尝试访问 Django 模板格式的列表中的元组时,我发现我无法使用 a[ 0 ][ 1 ] 访问它,我不得不使用a.0.1。

假设 a 是这样的

a = [ 
    ( 'a', 'apple' ), 
    ( 'b', 'bee'   ), 
] 

为什么Django模板语言不支持a[0][1]?在普通的 Python 编程中,a.0.1 会给您一个语法错误。

请您参考如下方法:

the template API 上的 Django 文档很好地解释这一点:

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

The template system uses the first lookup type that works. It's short-circuit logic. Here are a few examples:

>>> from django.template import Context, Template 
>>> t = Template("My name is {{ person.first_name }}.") 
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}} 
>>> t.render(Context(d)) 
"My name is Joe." 
 
>>> class PersonClass: pass 
>>> p = PersonClass() 
>>> p.first_name = "Ron" 
>>> p.last_name = "Nasty" 
>>> t.render(Context({"person": p})) 
"My name is Ron." 
 
>>> t = Template("The first stooge in the list is {{ stooges.0 }}.") 
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]}) 
>>> t.render(c) 
"The first stooge in the list is Larry." 

Variable._resolve_lookup in django.templates.base似乎是负责此的功能,并且没有太大变化since the oldest revision I can find