Home >>Django Tutorial >Django Templates
In Django, the template is used to generate dynamic HTML pages. A template consists of static parts of the desired HTML output as well as some special syntax that describe how the dynamic content will be inserted.
We can't write python code in HTML because the code is only interpreted by python interpreter not the browser. Django template engine is used to separate the HTML design from the python code and allows us to build dynamic web pages.
This function takes three different parameters −
We have to provide some entries in settings.py file to configure the template system.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
Django’s template engine provides a mini-language to define the user-facing layer of the application.
Displaying Variables
The template replaces the variable with the variable sent by the view in the third parameter of the render function.
//hello.html
<html> <body> Hello World!!!<p>Today is {{today}}</p> </body> </html>
//Now our view will change like this:
def hello(request): today = datetime.datetime.now().date() return render(request, "hello.html", {"today" : today})
After accessing the URL/myapp/hello we will get the following output :
If the variable is not a string then the Django will use the __str__ method to display it and using the same principle we can also access an object attribute just like the Python.
Filters
Filters help us in modifying the variables at display time. Filters structure looks like this: {{var|filters}}.
Some examples −