0% found this document useful (0 votes)
48 views22 pages

L06-Django Template Language

Uploaded by

123 456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views22 pages

L06-Django Template Language

Uploaded by

123 456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

CSC309 – LECTURE 06

DJANGO TEMPLATE LANGUAGE


Khai Truong
Announcements
Not on a team of 4?
● Please contact me (via email: [email protected] )
and let me know who is on your team currently
● I will start to put people on teams.

Booking office hours/mentoring sessions


● https://outlook.office365.com/owa/calendar/CSC309Spring2024@
utoronto.onmicrosoft.com/bookings/
Volunteer note taker(s)
Accessibility Services is seeking volunteer note takers for students in this class who are registered in Accessibility Services. By volunteering to
take notes for students with disabilities, you are making a positive contribution to their academic success. By volunteering as a note-taker,
you will benefit as well - It is an excellent way to improve your own note-taking skills and to maintain consistent class attendance. At the end
of term, we would be happy to provide a Certificate of Appreciation for your hard work. To request a Certificate of Appreciation please fill out the
form at this link: Certificate of Appreciation or email us at at [email protected]. You may also qualify for a Co-Curricular Record by
registering your volunteer work on Folio before the end of June. We also have a draw for qualifying volunteers throughout the academic year.
Steps to Register as a Volunteer :
1. Register Online as a Volunteer Note-Taker at: https://clockwork.studentlife.utoronto.ca/custom/misc/home.aspx
2. For a step-to-step guide please follow this link to the Volunteer Notetaking Portal Guide
3. Click on Volunteer Notetakers, and sign in using your UTORid
4. Select the course(s) you wish to take notes for. Please note: you do NOT need to upload sample notes or be selected as a volunteer to
begin uploading your notes.
5. Start uploading notes.
Email us at [email protected] if you have questions or require any assistance with uploading notes. If you are no longer able to
upload notes for a course, please also let us know immediately .
For more information about the Accessibility Services Peer Notetaking program, please visit Student Life Volunteer Note Taking .
Thank you for your support and for making notes more accessible for our students.
AS Note-taking Team
Architectural design patterns
General approach to recurring problems in software architectural
design
Clarify and define components and their responsibilities
Frequently used terms:
● Model: handles data storage, forms logical structure of the
application
○ Can include business logic that handles, modifies, or
processes data
● View: handles user interface and displaying data
Model-View-Controller (MVC)
Design pattern which decouples user-interface (view), data (model),
and logic (controller) Alerts
Output controller of Controller
event
Updates
Updates view
model
as needed
View

Updates

Follows “fat model, skinny Input Model


controller” principle
Java AWT/Swing
Model-View-Controller (MVC)
View → GUI components (e.g., JTable,
JTextComponent)
Model → component specific data
container objects (e.g., TableModel,
Document)
Controller → class objects
implementing various Listener
interfaces

https://docs.oracle.com/javase/8/docs/api/javax/swing/text/JTextComponent.html
Django
Model-View-Template (MVT)
Design pattern which also decouples user-interface (template), data
(model), and logic (view)

● Django model ↦ MVC model


● Django view ↦ MVC controller
● Django template ↦ MVC view

applies template
● URL dispatcher is part of
MVC controller

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page
Django Template Language
DTL supports imperative programming features
Data passed from view to template via context
Variables are replaced by data from context
Tags control the logic of the template
Data passed from view to template via context

from django.shortcuts import render


def howdy(request,name,age):
error = None
code = 200 # success
context = {
"error" : error,
"name" : name,
"age" : age,
}
return render(request, 'sayhello/howdy.html', context, status=code)

From Monday’s lecture


Variables are replaced by data from context
sayhello/howdy.html
<html>
<head>
<title>Howdy!</title>
</head>
<body>
<p>Howdy, {{name}}</p>
<p>You are {{age}} years old today!</p>
</body>
</html>
Tags control the logic of the template
for loop if, elif, else
<ul> {% if ticket_unavailable %}
{% for athlete in athlete_list %} <p>Tickets are not available.</p>
<li>{{ forloop.counter }}: {% elif tickets %}
{{ athlete.name }}</li> <p>Number of tickets: {{tickets}}.</p>
{% endfor %} {% else %}
</ul> <p>Tickets are sold out.</p>
{% endif %}
Django template tips
Use {% url 'namespace:name' %} to map named URL to user URL,
instead of hard coding it
if tags can take relational operators, such as:
● {% if myvar == "x“ %}
● {% if user in user_list %}
● {% if myval > 500 %}

Members variable, dictionary lookup, index access all use dot operator
● {{user_list.0}}
● {{request.POST.username}}

Remember to add comments to your code, such as:


{# hello, this is a comment #}
Django template filters
Similar to functions that modify a variable
Syntax: {{variable|filter}}
List of tags and filters:
● https://docs.djangoproject.com/en/4.2/ref/templates/builtins/

Filters can be changed


● E.g., {{value|first|upper}}
Examples
Django template filters
length
● Similar to Python len()
● E.g., {{my_list|length}}
lower
● Similar to str.lower()
● E.g., {{mytext|lower}}
time
● Formats time object
● E.g., {{value|time:”H:i”}} → 10:05
Template inheritance
Most powerful and complex part of Django’s template engine
Allows for a base “skeleton” template that contains all the common
elements of site to be created with defined blocks that child
templates can override
base.html
Template inheritance
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
{% block staticfiles %}
<link rel="stylesheet" href="{% static ‘/css/bootstrap.css’ %}">
{% endblock %}
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
child.html
Template inheritance
{% extends "base.html" %} extends must be on the first line
{% load static %}

{% block staticfiles %} child template does not inherit


{{ block.super }} tags loaded in parent
<link rel="stylesheet" href="{% static '/css/child.css' %}">
{% endblock %}

{% block title %}My child site{% endblock %}

{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
The sidebar block wasn’t defined…
what do you think will happen as a
result?
Root template folder
Typically, each template belongs to only one view and should be
placed inside their respective app’s folder
Some templates have common components across apps (e.g.,
navigation bar, footer, form elements, etc.)
Reusable templates can be placed in a root template directory
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ BASE_DIR / "templates" ],
'APP_DIRS': True,
'OPTIONS': {

},
Add this line to the project’s settings.py file
},
]
Include tag
The include tag allows you to include a sub-template (i.e., block of
content that is the same for many pages) inside the current
template.
Syntax: {% include template_name %}
Can pass additional context;
e.g., {% include"greeting.html" with person="Bob" %}
Can restrict context to only ones explicitly passed in;
e.g., {% include"greeting.html" with person="Bob" user=user only%}

Why use include when you can


extend?
You can only inherit from one parent
Summary
You have learned about Django’s Model-View-Template design pattern
and the basics of the Django Template Language
Learn more on your own:
https://docs.djangoproject.com/en/5.0/ref/templates/language/
Experiment, search online, and/or read reference manuals

Next week: The “model” in MVT


Much of this lecture was taken from content previously created by Jack Sun & Kianoosh Abbasi

Reproduction and/or sharing of course materials is prohibited. Course materials include lecture slides, course notes,
assignments, data and documents provided by the instructors. Course materials created by the instructors of this course
are their intellectual properties. They may not be shared, posted, rehosted, sold, or otherwise distributed and/or
modified without expressed permission from the authors. All such reproduction or dissemination is an infringement of
copyright and is prohibited. All rights are reserved by the instructors.

Thank you & questions?

You might also like