Django模板

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 又指什么?


在尝试学习Django之前,您真的应该先完成一份Python入门教程。 - Daniel Roseman
4个回答

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

第一个人(在引号内)表示Template期望的变量名。第二个人将你代码中创建的person变量分配给Contextperson变量,以传递给Template。第二个人可以是任何内容,只要与其声明相匹配即可。

这应该会使事情更加清楚:

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)

1
两个变量都需要被称为“person”才能在这个例子中使用吗?还是只是随意取的名字?
不,这只是随意取的名字。
“person”指的是什么?又是什么指的“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.')

0

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


0

{'person': person} 是一个标准的 Python 字典Context 构造函数需要一个字典,并生成一个适用于模板的上下文对象。通过 Template.render() 方法将上下文传递到模板中,然后获取最终结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接