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.

3.2 Context objects and the parts of a Template

3.3 Django shell

3.4 Rendering a Template

3.5 Common tags and filters

3.5.1 Conditional blocks

3.5.2 Looping blocks

3.5.3 Comment blocks

3.5.4 Verbatim blocks

3.5.5 Referencing URLs

3.5.6 Common filters

3.6 Using render() in a view

3.7 Escaping special characters

3.8 Composing templates out of blocks

3.8.1 Writing a base template file

3.8.2 Including an HTML snippet

3.9 Exercises

Summary