Chapter 8. Advanced Templates

Although most of your interactions with Django's template language will be in the role of template author, you may want to customize and extend the template engine-either to make it do something it doesn't already do, or to make your job easier in some other way.

This chapter delves deep into the guts of Django's template system. It covers what you need to know if you plan to extend the system or if you're just curious about how it works. It also covers the auto-escaping feature, a security measure you'll no doubt notice over time as you continue to use Django.

Template language review

First, let's quickly review a number of terms introduced in Chapter 3, Templates:

  • A template is a text document, or a normal Python string, that is marked up using the Django template language. A template can contain template tags and variables.
  • A template tag is a symbol within a template that does something. This definition is deliberately vague. For example, a template tag can produce content, serve as a control structure (an if statement or for loop), grab content from a database, or enable access to other template tags.

Template tags are surrounded by {% and %}:

        {% if is_logged_in %} 
            Thanks for logging in! 
        {% else %} 
            Please log in. 
        {% endif %} 
  • A variable is a symbol within a template that outputs a value.
  • Variable tags are surrounded by {{ and }}:
  • A context is a name->value mapping (similar to a Python dictionary) that is passed to a template.
  • A template renders a context by replacing the variable "holes" with values from the context and executing all template tags.

For more details about the basics of these terms, refer back to Chapter 3, Templates. The rest of this chapter discusses ways of extending the template engine. First, though, let's take a quick look at a few internals left out of Chapter 3, Templates, for simplicity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset