Reputation: 18271
I am doing a Django tutorial on Templates. I am currently at this code:
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.'
What I don't understand is this line:
c = Context({'person': person})
Do both variables need to be called person to be used in this example or is it just random?
What is 'person'
referring to and what is person
referring to?
Upvotes: 4
Views: 296
Reputation: 11
c = Context({'person': person})
Here the first 'person' in dictionary is variable name(key) where as other person represent the variable which you have declared in above line i.e.
t = Template('{{ student.name }} is {{ student.age }} years old.')
Context is a constructor,that takes one optional argument & its a dictionary mapping variable names to variable values. Call the Template object’s render() method with the context to “fill” the template:
to get more information visit given link
http://www.djangobook.com/en/2.0/chapter04.html
Upvotes: 0
Reputation: 798626
{'person': person}
is a standard Python dict. The Context
constructor takes a dict and produces a context object suitable for use in a template. The Template.render()
method is how you pass the context to the template, and receive the final result.
Upvotes: 0
Reputation: 188014
Do both variables need to be called person to be used in this example or is it just random?
No, this is just random.
What is 'person' refering to and what is person refering to?
First, the {}
is a dictionary object, which is the python terminology for an associative array or hash. It is basically an array with (almost) arbitrary keys.
So in your example, 'person'
would be the key, person
the value.
When this dictionary gets passed to the template, you can access your real objects (here, the person, with name, age, etc) by using the key, you choose before.
As an alternative example:
# 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.')
Upvotes: 1
Reputation: 59451
c = Context({'person': person})
The first person (within quotes) denotes the variable name that the Template
expects. The second person assigns the person
variable created in the second line of your code to the person variable of the Context
to be passed to the Template
. The second one can be anything, as long as it matches with its declaration.
This should clarify things a little bit:
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)
Upvotes: 3