3 Templates
This chapter covers
- Managing HTML-like code through templates
- Rendering templates based on context data
- Template tags and filters
- Using the
render()
shortcut inside views - Composing and inheriting templates for HTML reuse
This chapter introduces you to adding HTML content to your website. Django includes a templating engine that can compose and control text content, allowing you to create reusable pieces of HTML, managing it like you would manage your code.
3.1 Where to use templates
In the previous chapter, you learned how to start a simple website by creating a Django project. Inside the project, you created your first app and your first view. To keep things simple, an important thing got left out: HTML. A website isn’t much of a website without it. The purpose of a Django view is to return content, typically for a single web page. Your first view was the Credits page, showing the website’s authors. This view used plain text; however, instead of returning plain text, most of your views will return HTML.
The Django Template Engine is a collection of tools that allow you to compose and control text in a way similar to how inheritance works in object-oriented programming. A header or footer can be declared in a separate file and then included in each page that is rendered. This isolates the text, and any changes automatically get propagated throughout your site.