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

2024-06-16 11:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在FlaskWeb框架中使用方括号或点表示法有什么区别?这两种方法似乎都有效,例如:

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

两者有什么区别?文件似乎倾向于使用点符号,所以是否应该在所有案例中使用?在


Tags: 文件方法脚本框架模板session符号username
3条回答

这是Jinja2的一个特性,请参见模板设计器文档的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将首先查找属性,然后查找。由于Flask ^{} object是一个字典,这意味着您可能会得到错误的结果;如果您在会话中的键get下存储了数据,session.get返回一个dictionary方法,但是session['get']将返回与'get'键关联的实际值。在

相关问题 更多 >