How to use templates in Django?
In Django, templates are a way to generate HTML pages by embedding dynamic data and logic. The following are the basic steps for using Django templates:
- Create a template file: Create a new folder named ‘templates’ in the Django project, then create HTML files within that folder as template files. You can use Django’s template syntax, such as variables like {{ variable }} and loops like {% for item in list %}.
- Set the template path: In the settings.py file, configure the path of the template files by adding the templates folder to the DIRS list in TEMPLATES.
- Load the template in the view: Use the render method in the view function to load the template file and pass the necessary data to the template.
from django.shortcuts import render
def my_view(request):
data = {'name': 'Alice', 'age': 25}
return render(request, 'my_template.html', data)
- Use data in templates: Data passed to the template file can be used to display dynamic content using template syntax.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Template</title>
</head>
<body>
<h1>Hello, {{ name }}</h1>
<p>Your age is {{ age }}</p>
</body>
</html>
- Use the template: Finally, in the view function, return the generated HTML page using the render method.
By following the above steps, you can use templates in a Django project to generate dynamic HTML pages.