Flask 模板中点符号和方括号之间的区别

Difference between dot notation and square brackets in Flask templates

在 Flask web 框架中使用方括号或点符号有什么区别?两者似乎都有效,例如:

在 Python 脚本中我可以设置 session['username'] = 'Geraint'。然后我可以使用 {{ session['username'] }}{{ session.username }}

访问它的模板

两者有什么区别?文档似乎支持点符号,所以应该在 所有 情况下使用点符号吗?

这是 Jinja2 的一个特性,参见 Template Designer 文档的 Variables section

You can use a dot (.) to access attributes of a variable in addition to the standard Python __getitem__ “subscript” syntax ([]).

这是一个便利功能:

For the sake of convenience, foo.bar in Jinja2 does the following things on the Python layer:

  • check for an attribute called bar on foo (getattr(foo, 'bar'))
  • if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))
  • if there is not, return an undefined object.

foo['bar'] works mostly the same with a small difference in sequence:

  • check for an item 'bar' in foo. (foo.__getitem__('bar'))
  • if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))
  • if there is not, return an undefined object.

This is important if an object has an item and attribute with the same name. Additionally, the attr() filter only looks up attributes.

因此,如果您使用属性访问 ({{ session.username }}),那么 Jinja2 将首先查找 属性 ,然后查找 key.由于 Flask session object 是一个字典,这意味着您可能会得到错误的结果;如果您在会话中的键 get 下存储了数据,session.get return 是一个字典方法,但是 session['get'] 将 return 与 'get'键。