这背后的原因是您的模板文件可以有很多占位符,它需要知道如何区分所有这些占位符。
例如,你可以有下面的模板:
<!DOCTYPE html>
<html lang="en">
<head>
<title> {{ page_title }}
</head>
<body>
{{ page_body }}
</body>
</html>
现在想想,你会不会有变量的名字,请问是需要呈现的页面和注入的变量而不是函数的占位符会知道在哪里放置每个变量?这就是为什么你实际上以key=value
的形式传递字典,并且可以将多个键和值传递给该函数,而不会限制函数知道期望的参数数量。
在上述例子中,该呼叫到render_template
功能将是:
render_template('page.html', page_title='this is my title', page_body='this is my body')
这是函数的实际签名(从here截取):
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the variables that should be available in the
context of the template.
"""
的**context
是Python的方式来聚合传递给函数的所有参数key=value
,并将它们作为字典形式使用:
{'key1': value1, 'key2': value2, ...}
而且我猜想函数本身或被调用的子函数正在解释模板页面,并寻找模板中提供的变量名称,其中的变量名称与变量名称相对应。
长话短说,这种方式的功能是足够通用的,每个人都可以传递尽可能多的参数,并且该功能能够正确呈现模板页面。
除非您将该变量作为关键字arg传递,否则该模板如何知道变量被调用? – davidism