Django templates define the layout and final formatting sent to end users after a view method is finished processing a request. In this chapter, you'll learn the syntax used by Django templates, the configuration options available for Django templates, as well as the various Django template constructs (e.g. filters, tags, context processors) that allow you to create elaborate layouts and apply formatting to the content presented to end users.

Django template syntax

Although there are over one hundred built-in constructs that help you build Django templates -- all of which you'll learn as this chapter progresses -- to start out, these are the most important syntax elements you need to recognize:

Any other syntax in Django templates besides these three variations is treated 'as is'. This means that if a template declares the Hypertext Markup Language (HTML) heading <h1>Welcome!</h1>, a user will get a large HTML heading. It's that simple.

But let's take a look at one not so obvious Django template syntax behavior that's important you understand right away, since it's a recurring theme in practically everything associated with Django templates.

Auto-escaping: HTML and erring on the safe side

Django projects operate on the web, so by default all templates are assumed to produce HTML. While this is a reasonable assumption, it isn't, until you face one of two things:

So how could you possibly introduce invalid HTML or even dangerous content into Django templates ? Well it's the Internet, it's content from other users or providers that can end up in your Django templates that can cause problems (e.g. data submitted by users, third party services, content from databases).

The issue isn't content you place directly in Django templates -- that's given to be valid since you type it in -- the issue is dynamic content placed through variables, tags, filters and context processors, which has the potential to come from anywhere. Let's analyze this further with the following variables: