<p>这是Jinja2的一个特性,请参见<em>模板设计器</em>文档的<a href="http://jinja.pocoo.org/docs/dev/templates/#variables" rel="nofollow"><em>Variables</em> section</a>:</p>
<blockquote>
<p>You can use a dot (<code>.</code>) to access attributes of a variable in addition to the standard Python <code>__getitem__</code> “subscript” syntax (<code>[]</code>).</p>
</blockquote>
<p>这是一个<em>便利</em>功能:</p>
<blockquote>
<p>For the sake of convenience, <code>foo.bar</code> in Jinja2 does the following things on the Python layer:</p>
<ul>
<li>check for an attribute called <em>bar</em> on <em>foo</em> (<code>getattr(foo, 'bar')</code>)</li>
<li>if there is not, check for an item <code>'bar'</code> in <em>foo</em> (<code>foo.__getitem__('bar')</code>)</li>
<li>if there is not, return an undefined object.</li>
</ul>
<p><code>foo['bar']</code> works mostly the same with a small difference in sequence:</p>
<ul>
<li>check for an item <code>'bar'</code> in <em>foo</em>. (<code>foo.__getitem__('bar')</code>)</li>
<li>if there is not, check for an attribute called <em>bar</em> on <em>foo</em>. (<code>getattr(foo, 'bar')</code>)</li>
<li>if there is not, return an undefined object.</li>
</ul>
<p>This is important if an object has an item and attribute with the same name. Additionally, the <code>attr()</code> filter only looks up attributes.</p>
</blockquote>
<p>因此,如果使用属性访问(<code>{{ session.username }}</code>),那么Jinja2将首先查找<em>属性</em>,然后查找<em>键</em>。由于<a href="http://flask.pocoo.org/docs/0.10/api/#flask.session" rel="nofollow">Flask ^{<cd2>} object</a>是一个字典,这意味着您可能会得到错误的结果;如果您在会话中的键<code>get</code>下存储了数据,<code>session.get</code>返回一个dictionary方法,但是<code>session['get']</code>将返回与<code>'get'</code>键关联的实际值。在</p>