Django comes with a built-in template engine that allows you to dynamically generate HTML, XML, or other markup languages using Python. Template loaders in Django are responsible for loading templates from various sources, such as the filesystem, database, or remote locations.
Here's a basic overview of how to use Django's built-in template loaders:
Make sure your Django project is properly configured to use templates. In your settings.py
file, you should have a setting called TEMPLATES
that defines the template engine configuration. Here's a minimal example:
python# settings.py
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',
],
},
},
]
In this example:
'BACKEND'
specifies the template engine to use (django.template.backends.django.DjangoTemplates
).'DIRS'
is a list of directories where Django should look for templates. It includes the default 'templates' directory in your app.'APP_DIRS'
tells Django to look for templates in each app's 'templates' directory.'OPTIONS'
allows you to configure various options, including context processors.Create an HTML file in one of the specified template directories. For example, if you have an app named 'myapp,' you might create a file at myapp/templates/myapp/my_template.html
.
html<!-- my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Title{% endblock %}</title>
</head>
<body>
<h1>{% block content %}Hello, World!{% endblock %}</h1>
</body>
</html>
Now, you can use this template in a Django view. In your views, you can render the template and pass context data.
python# views.py
from django.shortcuts import render
def my_view(request):
context = {'name': 'John'}
return render(request, 'myapp/my_template.html', context)
In this example, myapp/my_template.html
is the path to your template, and context
is a dictionary containing data to be used in the template.
Django's template engine will automatically load the template using the configured template loaders and render the HTML with the provided context data.
Remember to run python manage.py runserver
to see the result in your browser.
This is a basic example, and Django provides more advanced features for template inheritance, custom template tags, and filters. Refer to the Django documentation for more details: https://docs.djangoproject.com/en/stable/topics/templates/