4

我正在做一个关于模板的 Django 教程。我目前在这个代码:

from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
u'Sally is 43 years old.'

我不明白的是这一行:

c = Context({'person': person})

在这个例子中,这两个变量都需要被称为 person 还是只是随机的?

'person'指的是什么,指的是什么person

4

4 回答 4

3
c = Context({'person': person})

第一人称(引号内)表示Template期望的变量名。第二个人将代码第二行中创建的变量person分配给要传递给. 第二个可以是任何东西,只要它与它的声明相匹配。ContextTemplate

这应该澄清一些事情:

from django.template import Template, Context
>>> someone = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ student.name }} is {{ student.age }} years old.')
>>> c = Context({'student': someone})
>>> t.render(c)
于 2010-06-23T08:06:36.450 回答
1

在这个例子中,这两个变量都需要被称为 person 还是只是随机的?

不,这只是随机的。

“人”指的是什么,人指的是什么?

首先,{}是一个字典对象,它是关联数组或哈希的python术语。它基本上是一个带有(几乎)任意键的数组。

所以在你的例子中,'person'将是关键,person价值。

当这个字典被传递给模板时,你可以使用你之前选择的键来访问你的真实对象(这里是人、名字、年龄等)。

作为替代示例:

# we just use another key here (x)
c = Context({'x': person})

# this would yield the same results as the original example
t = Template('{{ x.name }} is {{ x.age }} years old.')
于 2010-06-23T08:08:01.843 回答
0

{'person': person}是一个标准的 Python dict。构造Context函数接受一个字典并生成一个适合在模板中使用的上下文对象。该Template.render()方法是将上下文传递给模板并接收最终结果的方式。

于 2010-06-23T08:18:49.503 回答
0

c = Context({'person': person})
这里字典中的第一个“人”是变量名(键),其中其他人代表您在上面一行中声明的变量,即 t = Template('{{ student. name }} 是 {{ student.age }} 岁。') Context是一个构造函数,它接受一个可选参数,它是一个将变量名映射到变量值的字典。使用上下文调用 Template 对象的 render() 方法以“填充”模板:要获取更多信息,请访问给定链接 http://www.djangobook.com/en/2.0/chapter04.html

于 2015-02-20T07:57:27.020 回答