Lec6 - Templates
Lec6 - Templates
COMP 8347
Usama Mir
[email protected]
1
Django Templates
Topics
Introduction to Templates
Django Template Language
Template Inheritance
Including Static Files in Templates
2
Review MTV Architecture
Model Browser
Response Request
Represent data (client)
organization; defines a
table in a database.
mplate
URL
Contain information to View
configs.
be sent to client; help Django
generate final HTML.
3
Templates
4
Shortcut Functions
django.shortcuts: A package that collects helper
functions and classes.
“span” multiple levels of MTV.
these functions/classes introduce controlled
coupling for convenience.
5
Render()
render(request, template_name, context=None, content_type=None,
status=None, using=None)
Required arguments
content_type: The MIME type to use for the resulting document. Defaults to
'text/html’.
status: The status code for the response. Defaults to 200.
using: The NAME of a template engine to use for loading the template. Ex.
BACKEND, DIR, APP_DIR etc
www.webforefront.com/django/1.11/customizedjangotemplates.html
6
An Example
from myapp.models import Book
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Book
def my_view(request):
def my_view(request):
# View code here...
# View code here...
books = Book.objects.all()
books = Book.objects.all()
response=HttpResponse()
return render(request,
for item in books:
'myapp/index.html', { ‘booklist':
para= ‘<p>’ + item.title+ ‘</p>’
books })
response.write(para)
return response
7
Template Language Syntax
8
Variables
9
The Dot-lookup Syntax
10
Filters
11
Tags
12
for Tag
13
if, elif, else Tags
Evaluates a variable
if the variable is “true”, then the contents of the block
are displayed
{% if my_list|length > 5 %}
<p> Number of selected items: {{ my_list|length }} </p>
{% elif my_list %}
<p> Only a few items were selected </p>
{% else %}
<p> {{my_list|default: ‘Nothing selected.’}} </p>
{% endif %}
14
url Tag
15
Removing Hardcoded URLs
urlpatterns = [
path(r'<int:emp_id>/', views.detail, name='detail'),
]
Matching url: myapp/5/
A hardcoded link in template file:
<a href="/myapp/{{ author.id }}/">{{ author.name }}</a>
hard to change URLs on projects with many templates
Solution: use the {% url %} template tag, if name argument is defined in the
corresponding urls.py
<a href="{% url ‘myapp:detail’ author.id %}">{{author.name }}</a>
looks up URL definition from the myapp.urls module
path(‘<int:author_id>/’, views.detail, name='detail')
If you want to change the URL
Matching url: myapp/5/ → myapp/emp_info/5/
path(‘emp_info/<int:emp_id>/’, views.detail, name='detail’)
Don’t need to change anything in template file
16
Namespacing URL Names
Adding namespaces allows Django to distinguish between views with same
names in different APPs.
add namespace in app level urls.py (after import instructions)
app_name = ‘myapp2’
URL definition from the myapp2.urls module
path(’<int:author_id>/', views.detail, name='detail')
In template file, refer to it as
<a href="{% url ‘myapp2:detail’ author.id %}">{{author.name}}</a>
Assuming author.id=2, url tag will output string: /myapp/2 /
Final HTML string: <a href=“/myapp/2 / ">{{author.name}}</a>
17
Template Inheritance
Template inheritance: allows you to build a base “skeleton” template that
contains all the common elements of your site.
defines blocks that child templates can override
block Tag: Used in base template to define blocks that can be
overridden by child templates.
tells template engine that a child template may override those
portions of the template
<title>{% block title %}Hello World{% endblock %}</title>
extends Tag: Used in child template
tells the template engine that this template “extends” another
template.
18
Base&Child Templates
<!DOCTYPE html>
<html lang="en"> {% extends "base.html" %}
<head>
<link rel="stylesheet" href="style.css" /> {% block title %}My amazing blog{%
</html>
load Tag
load Tag: Loads a custom template tag set
{% load somelibrary package.otherlibrary %}
Ex.
<!DOCTYPE html>
{% load static %}
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}"/>
More examples on:
https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/
20
Static Files
21
Shortcut function: get_object_or_404
22
An Example
Alternatively,
from django.shortcuts import get_object_or_404
def my_view(request):
my_object = get_object_or_404(MyModel, pk=1)
23
Other Shortcut Functions
https://docs.djangoproject.com/en/4.1/topics/http/short
cuts/
24
References
https://docs.djangoproject.com/en/4.1/topics/templates/
https://docs.djangoproject.com/en/4.1/topics/http/short
cuts/
https://docs.djangoproject.com/en/4.1/howto/static-
files/
25