SlideShare a Scribd company logo
1 of 20
Ch4 Templates
8/29/2015
Templates
• Using the Template System
• Basic Template Tags and Filters
• Template Loading
• Template Inheritance
This Django template
describes an HTML page
Using the Template System
1. Create a Template object by providing the raw
template code as a string.
2. Call the render() method of the Template object
with a given set of variables (the context). This
returns a fully rendered template as a string,
with all of the variables and template tags
evaluated according to the context.
Creating Template Objects
The easiest way to create a Template object is to
instantiate it directly. Running python manage.py shell
instead of just python.
The system raises a TemplateSyntaxError exception for
any of the following cases:
Invalid tags
Invalid arguments to valid tags
Invalid filters
Invalid arguments to valid filters
Invalid template syntax
Unclosed tags (for tags that require closing tags)
Rendering a Template
Multiple Contexts, Same
Template
Context Variable Lookup
1. Dictionary lookup (e.g., foo["bar"])
2. Attribute lookup (e.g., foo.bar)
3. Method call (e.g., foo.bar())
4. List-index lookup (e.g., foo[2])
• Method Call Behavior
• If, during the method lookup, a method raises an exception,
the exception will be propagated, unless the exception has
an attribute silent_variable_failure whose value is True. If
the exception does have a silent_variable_failure attribute,
the variable will render as an empty string.
• A method call will only work if the method has no required
arguments. Otherwise, the system will move to the next
lookup type (list-index lookup).
• Some methods have side effects, and it would be foolish at
best, and possibly even a security hole, to allow the
template system to access them.
• How Invalid Variables Are Handled
• If a variable doesn’t exist, the template system renders it as
an empty string, failing silently.
Playing with Context Objects
A context is simply a set of template variable names
and their associated values.
Most of the time, you’ll instantiate Context objects
by passing in a fully populated dictionary to
Context(). But you can add and delete items from a
Context object once it’s been instantiated, too,
Basic Template Tags
and Filters
Tag
• if / else
And, Or, Not, elif
• for
forloop.counter
forloop.counter0
forloop.revcounter
forloop.revcounter0
forloop.first
forloop.last
forloop.parentloop
• ifequal / ifnotequal
• comments
Invalid examples
An empty list ([])
An empty tuple (())
An empty dictionary ({})
An empty string ('')
Zero (0)
The special object None
The object False (obviously)
Custom objects that define their own Boolean context
behavior (this is advanced Python usage)
False in a Boolean context
Filter
• {{ name|lower }}:Do not put any space character
before and after the pipe.
• {{ my_list|first|upper }}:Filters can be chained.
• {{ bio|truncatewords:"30" }}:Double quotes only.
• {{ pub_date|date:"F j, Y" }}
Template Loading
Template Loading
• render_to_response()
• The locals() Trick
• Subdirectories in get_template()
• The include Template Tag
Template Inheritance
1. Create a base.html template that holds the main
look and feel of your site.
2. Create a base_SECTION.html template for each
“section” of your site (e.g., base_photos.html
and base_forum.html).
3. Create individual templates for each type of
page, such as a forum page or a photo gallery.
Template Inheritance
HsuanWen Liu
“Thank you.”

More Related Content

What's hot

What's hot (18)

30csharp
30csharp30csharp
30csharp
 
Java Tutorial Lab 8
Java Tutorial Lab 8Java Tutorial Lab 8
Java Tutorial Lab 8
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Page Fragments как развитие идеи Page Object паттерна
Page Fragments как развитие идеи Page Object паттернаPage Fragments как развитие идеи Page Object паттерна
Page Fragments как развитие идеи Page Object паттерна
 
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals   maksym moskvychevTwig internals - Maksym MoskvychevTwig internals   maksym moskvychev
Twig internals - Maksym MoskvychevTwig internals maksym moskvychev
 
Python with data Sciences
Python with data SciencesPython with data Sciences
Python with data Sciences
 
Java Tutorial Lab 2
Java Tutorial Lab 2Java Tutorial Lab 2
Java Tutorial Lab 2
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Reflection power pointpresentation ppt
Reflection power pointpresentation pptReflection power pointpresentation ppt
Reflection power pointpresentation ppt
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Filter
FilterFilter
Filter
 
Quick Scala
Quick ScalaQuick Scala
Quick Scala
 
Namespace and methods
Namespace and methodsNamespace and methods
Namespace and methods
 
5. c sharp language overview part ii
5. c sharp language overview   part ii5. c sharp language overview   part ii
5. c sharp language overview part ii
 
Variable
VariableVariable
Variable
 
Bio solr building a better search for bioinformatics
Bio solr   building a better search for bioinformaticsBio solr   building a better search for bioinformatics
Bio solr building a better search for bioinformatics
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 

Viewers also liked

Deberian legalizar la marihuana en mèxico
Deberian legalizar la marihuana en mèxicoDeberian legalizar la marihuana en mèxico
Deberian legalizar la marihuana en mèxicoAlondra Sanchez
 
Delitos informáticos
Delitos informáticosDelitos informáticos
Delitos informáticosavilavidesy
 
Digitalisation of the Bank account
Digitalisation of the Bank accountDigitalisation of the Bank account
Digitalisation of the Bank accountEmma Lindgren
 
Concrete cloth
Concrete clothConcrete cloth
Concrete clotharyan922
 
HIST 5398 PAPER - Glankler FINAL
HIST 5398 PAPER - Glankler FINALHIST 5398 PAPER - Glankler FINAL
HIST 5398 PAPER - Glankler FINALEmily Glankler
 
“Serviced apartments” are “luxury apartments” www.quayapartments.co
“Serviced apartments” are “luxury apartments”   www.quayapartments.co“Serviced apartments” are “luxury apartments”   www.quayapartments.co
“Serviced apartments” are “luxury apartments” www.quayapartments.coQuay Aparntments
 
A natural history of the human mind
A natural history of the human mindA natural history of the human mind
A natural history of the human mindFrancys Subiaul
 

Viewers also liked (14)

Epae
EpaeEpae
Epae
 
Deberian legalizar la marihuana en mèxico
Deberian legalizar la marihuana en mèxicoDeberian legalizar la marihuana en mèxico
Deberian legalizar la marihuana en mèxico
 
Delitos informáticos
Delitos informáticosDelitos informáticos
Delitos informáticos
 
Vijay L&T
Vijay L&TVijay L&T
Vijay L&T
 
Administration
AdministrationAdministration
Administration
 
Digitalisation of the Bank account
Digitalisation of the Bank accountDigitalisation of the Bank account
Digitalisation of the Bank account
 
Berm protection
Berm protectionBerm protection
Berm protection
 
Concrete cloth
Concrete clothConcrete cloth
Concrete cloth
 
Concrete Canvas
Concrete CanvasConcrete Canvas
Concrete Canvas
 
CV
CVCV
CV
 
Unidad 4 funciones matemáticas
Unidad 4 funciones matemáticas Unidad 4 funciones matemáticas
Unidad 4 funciones matemáticas
 
HIST 5398 PAPER - Glankler FINAL
HIST 5398 PAPER - Glankler FINALHIST 5398 PAPER - Glankler FINAL
HIST 5398 PAPER - Glankler FINAL
 
“Serviced apartments” are “luxury apartments” www.quayapartments.co
“Serviced apartments” are “luxury apartments”   www.quayapartments.co“Serviced apartments” are “luxury apartments”   www.quayapartments.co
“Serviced apartments” are “luxury apartments” www.quayapartments.co
 
A natural history of the human mind
A natural history of the human mindA natural history of the human mind
A natural history of the human mind
 

Similar to Learning Web Development with Django - Templates

Similar to Learning Web Development with Django - Templates (20)

Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Introduction to Python and Django
Introduction to Python and DjangoIntroduction to Python and Django
Introduction to Python and Django
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Java
JavaJava
Java
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
AI_2nd Lab.pptx
AI_2nd Lab.pptxAI_2nd Lab.pptx
AI_2nd Lab.pptx
 
About Python
About PythonAbout Python
About Python
 
Javasession6
Javasession6Javasession6
Javasession6
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Java basics
Java basicsJava basics
Java basics
 
Collection
CollectionCollection
Collection
 
Python Basics.pptx
Python Basics.pptxPython Basics.pptx
Python Basics.pptx
 

Recently uploaded

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Learning Web Development with Django - Templates

  • 2. Templates • Using the Template System • Basic Template Tags and Filters • Template Loading • Template Inheritance
  • 5. 1. Create a Template object by providing the raw template code as a string. 2. Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.
  • 6. Creating Template Objects The easiest way to create a Template object is to instantiate it directly. Running python manage.py shell instead of just python. The system raises a TemplateSyntaxError exception for any of the following cases: Invalid tags Invalid arguments to valid tags Invalid filters Invalid arguments to valid filters Invalid template syntax Unclosed tags (for tags that require closing tags)
  • 9. Context Variable Lookup 1. Dictionary lookup (e.g., foo["bar"]) 2. Attribute lookup (e.g., foo.bar) 3. Method call (e.g., foo.bar()) 4. List-index lookup (e.g., foo[2])
  • 10. • Method Call Behavior • If, during the method lookup, a method raises an exception, the exception will be propagated, unless the exception has an attribute silent_variable_failure whose value is True. If the exception does have a silent_variable_failure attribute, the variable will render as an empty string. • A method call will only work if the method has no required arguments. Otherwise, the system will move to the next lookup type (list-index lookup). • Some methods have side effects, and it would be foolish at best, and possibly even a security hole, to allow the template system to access them. • How Invalid Variables Are Handled • If a variable doesn’t exist, the template system renders it as an empty string, failing silently.
  • 11. Playing with Context Objects A context is simply a set of template variable names and their associated values. Most of the time, you’ll instantiate Context objects by passing in a fully populated dictionary to Context(). But you can add and delete items from a Context object once it’s been instantiated, too,
  • 13. Tag • if / else And, Or, Not, elif • for forloop.counter forloop.counter0 forloop.revcounter forloop.revcounter0 forloop.first forloop.last forloop.parentloop • ifequal / ifnotequal • comments Invalid examples
  • 14. An empty list ([]) An empty tuple (()) An empty dictionary ({}) An empty string ('') Zero (0) The special object None The object False (obviously) Custom objects that define their own Boolean context behavior (this is advanced Python usage) False in a Boolean context
  • 15. Filter • {{ name|lower }}:Do not put any space character before and after the pipe. • {{ my_list|first|upper }}:Filters can be chained. • {{ bio|truncatewords:"30" }}:Double quotes only. • {{ pub_date|date:"F j, Y" }}
  • 17. Template Loading • render_to_response() • The locals() Trick • Subdirectories in get_template() • The include Template Tag
  • 19. 1. Create a base.html template that holds the main look and feel of your site. 2. Create a base_SECTION.html template for each “section” of your site (e.g., base_photos.html and base_forum.html). 3. Create individual templates for each type of page, such as a forum page or a photo gallery. Template Inheritance