Search code examples
djangotemplatesdjango-context

Django Template


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?


Solution

  • 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)