SlideShare a Scribd company logo
1 of 5
Download to read offline
The	
  Django	
  Book	
  
Chapter	
  4:	
  Templates	
  (Supplement)	
  
	
  
Speaker:	
  Vincent	
  Chien	
  
render_to_response	
  Django Book Documentation, Release 0.1
5.6.1 render_to_response()
We’ve shown you how to load a template, fill a Context and return an HttpResponse object with the result of
the rendered template. We’ve optimized it to use get_template() instead of hard-coding templates and template
paths. But it still requires a fair amount of typing to do those things. Because this is such a common idiom, Django
provides a shortcut that lets you load a template, render it and return an HttpResponse – all in one line of code.
This shortcut is a function called render_to_response(), which lives in the module django.shortcuts.
Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context
and HttpResponse objects manually – unless your employer judges your work by total lines of code written, that
is.
Here’s the ongoing current_datetime example rewritten to use render_to_response():
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response(’current_datetime.html’, {’current_date’: now})
What a difference! Let’s step through the code changes:
• We no longer have to import get_template, Template, Context, or HttpResponse. Instead, we
import django.shortcuts.render_to_response. The import datetime remains.
• Within the current_datetime function, we still calculate now, but the template loading, context creation,
(os.path.dirname), then joins that with templates in a cross-platform way (os.path.join), then
ensures that everything uses forward slashes instead of backslashes (in case of Windows).
While we’re on the topic of dynamic Python code in settings files, we should point out that it’s very important to
avoid Python errors in your settings file. If you introduce a syntax error, or a runtime error, your Django-powered
site will likely crash.
With TEMPLATE_DIRS set, the next step is to change the view code to use Django’s template-loading functionality
rather than hard-coding the template paths. Returning to our current_datetime view, let’s change it like so:
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def current_datetime(request):
now = datetime.datetime.now()
t = get_template(’current_datetime.html’)
html = t.render(Context({’current_date’: now}))
return HttpResponse(html)
50 Chapter 5. Chapter 4: Templates
Before	
  
A<er	
  
The	
  local()	
  Trick	
  
The first argument to render_to_response() is the name of the template to use. The second argument, if given,
should be a dictionary to use in creating a Context for that template. If you don’t provide a second argument,
render_to_response() will use an empty dictionary.
5.6.2 The locals() Trick
Consider our latest incarnation of current_datetime:
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response(’current_datetime.html’, {’current_date’: now})
Many times, as in this example, you’ll find yourself calculating some values, storing them in variables (e.g., now in
the preceding code), and sending those variables to the template. Particularly lazy programmers should note that it’s
slightly redundant to have to give names for temporary variables and give names for the template variables. Not only
is it redundant, but also it’s extra typing.
So if you’re one of those lazy programmers and you like keeping code particularly concise, you can take advantage of
a built-in Python function called locals(). It returns a dictionary mapping all local variable names to their values,
where “local” means all variables that have been defined within the current scope. Thus, the preceding view could be
rewritten like so:
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response(’current_datetime.html’, locals())
Here, instead of manually specifying the context dictionary as before, we pass the value of locals(), which will
include all variables defined at that point in the function’s execution. As a consequence, we’ve renamed the now
52 Chapter 5. Chapter 4: Templates
Consider our latest incarnation of current_datetime:
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response(’current_datetime.html’, {’current_date’: now})
Many times, as in this example, you’ll find yourself calculating some values, storing them in variables (e.g., now
the preceding code), and sending those variables to the template. Particularly lazy programmers should note that i
slightly redundant to have to give names for temporary variables and give names for the template variables. Not on
is it redundant, but also it’s extra typing.
So if you’re one of those lazy programmers and you like keeping code particularly concise, you can take advantage
a built-in Python function called locals(). It returns a dictionary mapping all local variable names to their valu
where “local” means all variables that have been defined within the current scope. Thus, the preceding view could
rewritten like so:
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response(’current_datetime.html’, locals())
Here, instead of manually specifying the context dictionary as before, we pass the value of locals(), which w
include all variables defined at that point in the function’s execution. As a consequence, we’ve renamed the n
52 Chapter 5. Chapter 4: Templat
Before	
  
A<er	
  
HTML	
  Classic	
  Way	
  Django Book Documentation, Release 0.1
# mypage.html
<html>
<body>
{% include "includes/nav.html" %}
<h1>{{ title }}</h1>
</body>
</html>
# includes/nav.html
<div id="nav">
You are in: {{ current_section }}
</div>
If you render mypage.html with a context containing current_section, then
the “included” template, as you would expect.
Template	
  Inheritance	
  
With an include-based strategy, headers and footers are easy. It’s the middle ground that’s messy. In this example, both
pages feature a title – <h1>My helpful timestamp site</h1> – but that title can’t fit into header.html
because the <title> on both pages is different. If we included the <h1> in the header, we’d have to include the
<title>, which wouldn’t allow us to customize it per page. See where this is going?
Django’s template inheritance system solves these problems. You can think of it as an “inside-out” version of server-
side includes. Instead of defining the snippets that are common, you define the snippets that are different.
The first step is to define a base template – a skeleton of your page that child templates will later fill in. Here’s a base
template for our ongoing example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>
This template, which we’ll call base.html, defines a simple HTML skeleton document that we’ll use for all the
pages on the site. It’s the job of child templates to override, or add to, or leave alone the contents of the blocks. (If
5.7. Template Inheritance 55
Django Book Documentation, Release 0.1
you’re following along, save this file to your template directory as base.html.)
We’re using a template tag here that you haven’t seen before: the {% block %} tag. All the {% block %} tags
do is tell the template engine that a child template may override those portions of the template.
Now that we have this base template, we can modify our existing current_datetime.html template to use it:
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
While we’re at it, let’s create a template for the hours_ahead view from Chapter 3. (If you’re following along with
code, we’ll leave it up to you to change hours_ahead to use the template system instead of hard-coded HTML.)
Here’s what that could look like:
{% extends "base.html" %}
Base.html	
  
Child	
  A	
  
Django Book Documentation, Release 0.1
you’re following along, save this file to your template directory as base.html.)
We’re using a template tag here that you haven’t seen before: the {% block %} tag. All the {% b
do is tell the template engine that a child template may override those portions of the template.
Now that we have this base template, we can modify our existing current_datetime.html tem
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
While we’re at it, let’s create a template for the hours_ahead view from Chapter 3. (If you’re follo
code, we’ll leave it up to you to change hours_ahead to use the template system instead of hard
Here’s what that could look like:
{% extends "base.html" %}
{% block title %}Future time{% endblock %}
{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}
Isn’t this beautiful? Each template contains only the code that’s unique to that template. No redund
you need to make a site-wide design change, just make the change to base.html, and all of the othe
immediately reflect the change.
Here’s how it works. When you load the template current_datetime.html, the template eng
Child	
  B	
  

More Related Content

What's hot

Perl web programming
Perl web programmingPerl web programming
Perl web programmingJohnny Pork
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJSTroy Miles
 
LocalizingStyleSheetsForHTMLOutputs
LocalizingStyleSheetsForHTMLOutputsLocalizingStyleSheetsForHTMLOutputs
LocalizingStyleSheetsForHTMLOutputsSuite Solutions
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and httpKaniska Mandal
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Eheinovex GmbH
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesJohn Brunswick
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfKaty Slemon
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPRobertGonzalez
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Knoldus Inc.
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perlDean Hamstead
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontendHeiko Hardt
 
How to add watermark to image using php
How to add watermark to image using phpHow to add watermark to image using php
How to add watermark to image using phpYourBlogCoach1
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 

What's hot (20)

Perl web programming
Perl web programmingPerl web programming
Perl web programming
 
SERVIET
SERVIETSERVIET
SERVIET
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
Angular 2 binding
Angular 2  bindingAngular 2  binding
Angular 2 binding
 
LocalizingStyleSheetsForHTMLOutputs
LocalizingStyleSheetsForHTMLOutputsLocalizingStyleSheetsForHTMLOutputs
LocalizingStyleSheetsForHTMLOutputs
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and http
 
React mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche EheReact mit TypeScript – eine glückliche Ehe
React mit TypeScript – eine glückliche Ehe
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Os Leonard
Os LeonardOs Leonard
Os Leonard
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
 
Testing the frontend
Testing the frontendTesting the frontend
Testing the frontend
 
How to add watermark to image using php
How to add watermark to image using phpHow to add watermark to image using php
How to add watermark to image using php
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 

Similar to The Django Book chapter 4 templates (supplement)

learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxbestboybulshaawi
 
Drupal8 render pipeline
Drupal8 render pipelineDrupal8 render pipeline
Drupal8 render pipelineMahesh Salaria
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsVincent Chien
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Rene Bakx
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slidesMasterCode.vn
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance TipsRavi Raj
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...LinnAlexandra
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesTikal Knowledge
 

Similar to The Django Book chapter 4 templates (supplement) (20)

learnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptxlearnpythondjangochapteroneintroduction.pptx
learnpythondjangochapteroneintroduction.pptx
 
Drupal8 render pipeline
Drupal8 render pipelineDrupal8 render pipeline
Drupal8 render pipeline
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfs
 
HTML literals, the JSX of the platform
HTML literals, the JSX of the platformHTML literals, the JSX of the platform
HTML literals, the JSX of the platform
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Actionview
ActionviewActionview
Actionview
 
6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides6 introduction-php-mvc-cakephp-m6-views-slides
6 introduction-php-mvc-cakephp-m6-views-slides
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
django
djangodjango
django
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
 
Jsp1
Jsp1Jsp1
Jsp1
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
 
React hooks
React hooksReact hooks
React hooks
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2
 
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfryanfarris8
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 

Recently uploaded (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in Uganda
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
 
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 

The Django Book chapter 4 templates (supplement)

  • 1. The  Django  Book   Chapter  4:  Templates  (Supplement)     Speaker:  Vincent  Chien  
  • 2. render_to_response  Django Book Documentation, Release 0.1 5.6.1 render_to_response() We’ve shown you how to load a template, fill a Context and return an HttpResponse object with the result of the rendered template. We’ve optimized it to use get_template() instead of hard-coding templates and template paths. But it still requires a fair amount of typing to do those things. Because this is such a common idiom, Django provides a shortcut that lets you load a template, render it and return an HttpResponse – all in one line of code. This shortcut is a function called render_to_response(), which lives in the module django.shortcuts. Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context and HttpResponse objects manually – unless your employer judges your work by total lines of code written, that is. Here’s the ongoing current_datetime example rewritten to use render_to_response(): from django.shortcuts import render_to_response import datetime def current_datetime(request): now = datetime.datetime.now() return render_to_response(’current_datetime.html’, {’current_date’: now}) What a difference! Let’s step through the code changes: • We no longer have to import get_template, Template, Context, or HttpResponse. Instead, we import django.shortcuts.render_to_response. The import datetime remains. • Within the current_datetime function, we still calculate now, but the template loading, context creation, (os.path.dirname), then joins that with templates in a cross-platform way (os.path.join), then ensures that everything uses forward slashes instead of backslashes (in case of Windows). While we’re on the topic of dynamic Python code in settings files, we should point out that it’s very important to avoid Python errors in your settings file. If you introduce a syntax error, or a runtime error, your Django-powered site will likely crash. With TEMPLATE_DIRS set, the next step is to change the view code to use Django’s template-loading functionality rather than hard-coding the template paths. Returning to our current_datetime view, let’s change it like so: from django.template.loader import get_template from django.template import Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() t = get_template(’current_datetime.html’) html = t.render(Context({’current_date’: now})) return HttpResponse(html) 50 Chapter 5. Chapter 4: Templates Before   A<er  
  • 3. The  local()  Trick   The first argument to render_to_response() is the name of the template to use. The second argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a second argument, render_to_response() will use an empty dictionary. 5.6.2 The locals() Trick Consider our latest incarnation of current_datetime: def current_datetime(request): now = datetime.datetime.now() return render_to_response(’current_datetime.html’, {’current_date’: now}) Many times, as in this example, you’ll find yourself calculating some values, storing them in variables (e.g., now in the preceding code), and sending those variables to the template. Particularly lazy programmers should note that it’s slightly redundant to have to give names for temporary variables and give names for the template variables. Not only is it redundant, but also it’s extra typing. So if you’re one of those lazy programmers and you like keeping code particularly concise, you can take advantage of a built-in Python function called locals(). It returns a dictionary mapping all local variable names to their values, where “local” means all variables that have been defined within the current scope. Thus, the preceding view could be rewritten like so: def current_datetime(request): current_date = datetime.datetime.now() return render_to_response(’current_datetime.html’, locals()) Here, instead of manually specifying the context dictionary as before, we pass the value of locals(), which will include all variables defined at that point in the function’s execution. As a consequence, we’ve renamed the now 52 Chapter 5. Chapter 4: Templates Consider our latest incarnation of current_datetime: def current_datetime(request): now = datetime.datetime.now() return render_to_response(’current_datetime.html’, {’current_date’: now}) Many times, as in this example, you’ll find yourself calculating some values, storing them in variables (e.g., now the preceding code), and sending those variables to the template. Particularly lazy programmers should note that i slightly redundant to have to give names for temporary variables and give names for the template variables. Not on is it redundant, but also it’s extra typing. So if you’re one of those lazy programmers and you like keeping code particularly concise, you can take advantage a built-in Python function called locals(). It returns a dictionary mapping all local variable names to their valu where “local” means all variables that have been defined within the current scope. Thus, the preceding view could rewritten like so: def current_datetime(request): current_date = datetime.datetime.now() return render_to_response(’current_datetime.html’, locals()) Here, instead of manually specifying the context dictionary as before, we pass the value of locals(), which w include all variables defined at that point in the function’s execution. As a consequence, we’ve renamed the n 52 Chapter 5. Chapter 4: Templat Before   A<er  
  • 4. HTML  Classic  Way  Django Book Documentation, Release 0.1 # mypage.html <html> <body> {% include "includes/nav.html" %} <h1>{{ title }}</h1> </body> </html> # includes/nav.html <div id="nav"> You are in: {{ current_section }} </div> If you render mypage.html with a context containing current_section, then the “included” template, as you would expect.
  • 5. Template  Inheritance   With an include-based strategy, headers and footers are easy. It’s the middle ground that’s messy. In this example, both pages feature a title – <h1>My helpful timestamp site</h1> – but that title can’t fit into header.html because the <title> on both pages is different. If we included the <h1> in the header, we’d have to include the <title>, which wouldn’t allow us to customize it per page. See where this is going? Django’s template inheritance system solves these problems. You can think of it as an “inside-out” version of server- side includes. Instead of defining the snippets that are common, you define the snippets that are different. The first step is to define a base template – a skeleton of your page that child templates will later fill in. Here’s a base template for our ongoing example: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>My helpful timestamp site</h1> {% block content %}{% endblock %} {% block footer %} <hr> <p>Thanks for visiting my site.</p> {% endblock %} </body> </html> This template, which we’ll call base.html, defines a simple HTML skeleton document that we’ll use for all the pages on the site. It’s the job of child templates to override, or add to, or leave alone the contents of the blocks. (If 5.7. Template Inheritance 55 Django Book Documentation, Release 0.1 you’re following along, save this file to your template directory as base.html.) We’re using a template tag here that you haven’t seen before: the {% block %} tag. All the {% block %} tags do is tell the template engine that a child template may override those portions of the template. Now that we have this base template, we can modify our existing current_datetime.html template to use it: {% extends "base.html" %} {% block title %}The current time{% endblock %} {% block content %} <p>It is now {{ current_date }}.</p> {% endblock %} While we’re at it, let’s create a template for the hours_ahead view from Chapter 3. (If you’re following along with code, we’ll leave it up to you to change hours_ahead to use the template system instead of hard-coded HTML.) Here’s what that could look like: {% extends "base.html" %} Base.html   Child  A   Django Book Documentation, Release 0.1 you’re following along, save this file to your template directory as base.html.) We’re using a template tag here that you haven’t seen before: the {% block %} tag. All the {% b do is tell the template engine that a child template may override those portions of the template. Now that we have this base template, we can modify our existing current_datetime.html tem {% extends "base.html" %} {% block title %}The current time{% endblock %} {% block content %} <p>It is now {{ current_date }}.</p> {% endblock %} While we’re at it, let’s create a template for the hours_ahead view from Chapter 3. (If you’re follo code, we’ll leave it up to you to change hours_ahead to use the template system instead of hard Here’s what that could look like: {% extends "base.html" %} {% block title %}Future time{% endblock %} {% block content %} <p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p> {% endblock %} Isn’t this beautiful? Each template contains only the code that’s unique to that template. No redund you need to make a site-wide design change, just make the change to base.html, and all of the othe immediately reflect the change. Here’s how it works. When you load the template current_datetime.html, the template eng Child  B