In Django, render()
is one of the most used functions that combines a template with a context dictionary and returns an HttpResponse
object with the rendered text.
render(request, template, {})
It takes the following three arguments.
request
: This is everything we receive from the user via the Internet.
template
: This is the template file that will be rendered.
context dictionary
: This is a dictionary where we store data that can be used by the template.
Let’s create a function in views.py
that will render a template with some context.
from django.shortcuts import render
def about(request):
template = "about.html"
context = {
fullName: "Shubham Kshariya",
age: 22,
destination: "Software Engineer"
}
return render(request, template , context)
First, we need to import the render
library from django.shortcuts
.
After that, we create an about
function where we define a template
file and a context
dictionary.
At the end of the function, we will invoke the render()
function and pass the required parameters to it.
The render()
function will return an HttpResponse
including the about.html
and context dictionary.
In order to render a dynamic variable in Django, it needs to be wrapped between {{
and }}
.
Check out how to create the about.html
to render data:
<html>
<head>
<title>User Information</title>
</head>
<body>
<p>Name: {{ fullName }}</p>
<p>Age: {{ age }}</p>
<p>Designation: {{ designation }}</p>
</body>
</html>
The dynamic portion of the file is wrapped between {{
and }}
.
We can also implement dictionary lookup, attribute lookup, and list-index lookups using a dot notation.
A comment can be also be added in the template like this.
{# single line comment #}
{% multiple line comment %}
Comments won’t be rendered in the output.