views:

36

answers:

3
+3  Q: 

Django Template

Dear Everybody

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 dont 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' refering to and what is person refering to?

Thanks

L

+2  A: 
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)
Amarghosh
+1  A: 

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.')
The MYYN
A: 

{'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.

Ignacio Vazquez-Abrams