Jinja2模板设计文档—变量

Template variables are defined by the context dictionary passed to the template.

模板变量通过传递给模板的上下文词典定义。

You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable.

您可以打乱通过应用传递到模板中的变量。变量可能有一些您可以使用的属性或者元素。变量中的属性依赖于应用所提供的变量。

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

除了使用标准Python的__getitem__“子脚本”语法([]),您还可以通过点(.)来访问一个变量的属性。

The following lines do the same thing:

如下两行是等效的:

{{ foo.bar }}
{{ foo['bar'] }}

It’s important to know that the outer double-curly braces are not part of the variable, but the print statement. If you access variables inside tags don’t put the braces around them.

需要我们了解的是,打印语句外面的双花括号并不是变量的一部分。你可以不使用花括号的方式访问标签中的变量。

If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated over, and to fail for every other operation.

如果一个变量或者属性不存在,您将会得到一个未定义的值。具体您能做什么依赖于应用的配置,默认情况,如果是打印或者迭代结束的情况下是得到一个空字符串,在其它操作则是执行失败。

Implementation

实现

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

为了方便,在Jinja2中foo.bar将在Python层面做如下事情:

  • check for an attribute called bar on foo (getattr(foo, 'bar'))
  • foo 变量中检查名称为bar 的属性(getattr(foo, 'bar'))
  • if there is not, check for an item 'bar' in foo (foo.__getitem__('bar'))
  • 如果没有,检查foo 中的元素 'bar' (foo.__getitem__('bar'))
  • if there is not, return an undefined object.
  • 如果没有,返回一个未定义的对象

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

foo['bar']工作方式在顺序上稍微有些不同:

  • check for an item 'bar' in foo. (foo.__getitem__('bar'))
  • 检查foo 中的元素 'bar' (foo.__getitem__('bar'))
  • if there is not, check for an attribute called bar on foo. (getattr(foo, 'bar'))
  • 如果没有,在 foo 变量中检查名称为bar 的属性(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.

一个对象具有相同名称的元素和属性很重要。另外,attr()过滤器仅仅关心属性。

如果引用本站的原创文章,请注明原文链接:,本站保留追究责任的权利!

发表评论