Django Template

I am doing a Django template tutorial. I am in 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 do not understand is the line:

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

Do I need to call both variables as the person to be used in this example, or just random?

What does 'person' refer to and what does person relate to?

+4
source share
4 answers
 c = Context({'person': person}) 

The first person (in quotation marks) denotes the name of the variable that Template expects. The second person assigns the person variable created in the second line of your code to the Context human variable that must be passed to the Template . The second can be anything if it matches his ad.

This should clarify the situation a 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) 
+3
source

Do I need to call both variables as the person to be used in this example, or just random?

No, it's just random.

What is the β€œman” that is referenced and what does the man refer to?

First, {} is a dictionary object, which is python terminology for an associative array or hash. This is basically an array with (almost) arbitrary keys.

So in your example, 'person' is the key, person value.

When this dictionary is passed to the template, you can access your real objects (here, a person with a name, age, etc.) using the key that you select earlier.

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.') 
+1
source

{'person': person} is a standard Python dict . The Context constructor takes a dict and creates a context object suitable for use in the template. The Template.render() method is how to pass the context to the template and get the final result.

0
source

c = Context ({'person': person})
Here, the first "person" in the dictionary is the name of the variable (key), where, when the other person represents the variable that you specified in the line above, i.e. t = Template ('{{student.name}} - {{student.age}} years.') Context is a constructor that takes one optional argument and its dictionary matching variable names for variable values. Call the render () method of the Template object with the context to "populate" the template: for more information, visit this link http://www.djangobook.com/en/2.0/chapter04.html

0
source

Source: https://habr.com/ru/post/1313621/


All Articles