Context And Variables
In a Django template you can use variables defined in your Python code. To do so, include these variables in a dictionary that is passed as the first argument to the render()
. This dictionary is known as context. So, the context defines the variables that you want to be available in a template. For example:
def index(request: HttpRequest) -> HttpResponse:
ctx = {"name": "John"}
return render(request, "myapp/index.html", ctx)
The second line of this function defines the ctx
dictionary in which you indicate that the name
variable (in the template) has the value "John"
. Now, in the index.html
template you can do:
<html>
<strong>Hello</strong>, <em>{{ name }}</em>!
</html>
And the result is, as expected:
What has happened here is that the render()
function has replaced the {{ name }}
portion of the template with the value assigned to that variable in the context (or, in other terms, in the case of a dictionary, the value that corresponds to that key in the context.) This method by which you indicate the name of a variable (defined in the context) between double curly braces to “print” its value in a template is one of the syntaxes of the Django template system that we mentioned above.
Let's add a few more things to the context to better illustrate this process:
def index(request: HttpRequest) -> HttpResponse:
ctx = {
"name": "John",
"courses": 5,
"current_course": "Python & Django"
}
return render(request, "myapp/index.html", ctx)
And in the template:
<html>
<strong>Hello</strong>, <em>{{ name }}</em>!
You did {{ courses }} courses and now you are doing the
{{ current_course }} course.
</html>
Now we see:
If the object between braces is a collection, you can access its elements from the template using a dot (note, again, that this is not Python syntax, although similar, but a specific syntax provided by the Django template system.) Examples:
def index(request: HttpRequest) -> HttpResponse:
ctx = {
"name": "John",
"courses": 5,
"current_course": {"name": "Python & Django", "time": "6:00 p.m."},
"previous_courses": ["Java", "PHP", "JavaScript", "Python"]
}
return render(request, "myapp/index.html", ctx)
And in index.html:
<html>
<strong>Hello</strong>, <em>{{ name }}</em>!
You did {{ courses }} courses and now you are doing the
{{ current_course.name }} course at {{ current_course.time }}
Your first course was {{ previous_courses.0 }}.
</html>