Book Image

Django 1.0 Template Development

Book Image

Django 1.0 Template Development

Overview of this book

Table of Contents (17 chapters)
Django 1.0 Template Development
Credits
About the Author
About the Reviewers
Preface
Index

Understanding the template system syntax


Now that we have a basic understanding of how the template system fits into the big picture, we can finally explore some basics of how it works.

As we discussed earlier, Django templates are basically just text files that have placeholders and simple logic in them. These placeholders are evaluated when the template is rendered, and Django replaces them with the values that go in their place.

Let's illustrate with a quick example of a template file:

<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ header }}</h1>
{% for name in names_list %}
{{ name.last|upper }}, {{ name.first|upper }}<br/>
{% endfor %}
</body>
</html>

Don't worry if you don't immediately grasp these concepts. We'll be running through a practical example of the syntax at the end of the chapter.

Context variable

If you recall the request-handling overview, we said the context was a special object that contained the values available to the template when it is rendered. We'll work through a practical example later in the chapter. For now, just think of it as a dictionary of variables that the template will be able to see (see the upcoming code note if you don't know what a Python dictionary is).

Variables

Variables are the basic placeholders in a Django template. They are identified by two curly brackets on each side:

My favorite color is {{ color }}.

When the Django template engine renders this page, it will see {{ color }} as a placeholder for the real value it is supposed to put in its place. It looks in the context for a key named color and finds the value associated. If our context has a key named color and an associated value of blue, the output would look like this:

My favorite color is blue.

Filters

Filters can format the output of variables in Django templates. They are identified by the use of a pipe symbol immediately following a template variable:

My favorite color is {{ color|upper }}.

In this example, upper is the filter we are using to modify the variable color. (Notice there is no space between the variable, the pipe, and the filter.) The upper filter will take the value of the variable and convert all the letters to upper case. (Specifically, it applies the Python string function upper() to the value.) Here is the resulting output:

My favorite color is BLUE.

Note

The filters don't change the value of the variables they modify, but just modify the way they are outputted. In our example, if you use {{ color }} somewhere else in your template without the template filter, it won't appear in upper case.

Django ships with a number of default filters that cover many common presentation-formatting needs. You can find them listed in the Django documentation at DjangoProject.com.

Tags

Template tags instruct the template rendering engine to perform some kind of action. They are identified by a curly bracket and percentage symbol, and often have an accompanying closing tag:

{% ifequal color 'blue' %}
  Wow, you like blue!
{% else %}
  Why don't you like blue?
{% endifequal %}

In this example, we are using the template tag ifequal. It takes two arguments, which means the values to be compared. Unlike Python code, we don't use parentheses or commas around the arguments. We just use a space between the template tag and each of the arguments. The tag also has a corresponding closing tag endifequal that tells the template engine we are done.

In this example, since the value of the variable is blue, we get this output:

Wow, you like blue!

Like filters, Django ships with a number of default tags that perform common logic in templates such as looping through sets of data. We'll be covering tags and filters in more depth in later chapters as well as writing our own custom tags.

When the templates are rendered, the tags are removed by the template engine. If you view the source of your output, you will not see your tags, though you will probably see a blank space where the tag was.

Comments

There are two kinds of comments we can use in Django templates: single-line and multi-line. Like comments in Python, you can leave yourself notes in a template or use comments to prevent a chunk of template code from being rendered by the template engine. Single-line comments are identified by a curly bracket and a hash mark (also known as the number sign or pound symbol):

{# Remember to move this down the page later #}
My favorite color is {{ color }}.

Multi-line comments are implemented as tags, and they have a corresponding endcomment tag:

{% comment %}
{% ifequal color 'blue' %}
  Wow, you like blue!
{% else %}
  Why don't you like blue?
{% endifequal %}
{% endcomment %}

In this example, the template engine ignores everything between the comment and endcomment tags. This is often used to troubleshoot and debug a section of template that isn't behaving properly.

Like template tags, single- and multi-line comments are removed from the resulting output by the template engine. They are not the same as HTML comments; you won't see them if you view the source of your output.

Code note: Python dictionaries

In case you are not familiar with Python dictionaries, here is a basic explanation.

A dictionary is one of Python's built-in data types, similar to hashes in other programming languages. It consists of keys and values. The key is the label used to identify the item, and the value is what it is equal to.

Here's an example:

>> mydictionary = {}
>> mydictionary['mykey'] = 'myvalue'
>> mydictionary['myotherkey'] = 10
>> print mydictionary
{'mykey': 'myvalue', 'myotherkey': 10}

The first line tells Python that we are creating a new dictionary called mydictionary. The empty curly brackets tell Python that we are creating a variable that is of type dictionary and not a string or integer. The next two lines add keys and values to the dictionary. The first adds a new key called mykey that has a value of myvalue. The second has a key of myotherkey and has a value of 10.

Note

We can mix numbers and strings as values of the keys. They don't all have to be the same type.

You can also create a dictionary in one step:

>> mydictionary = {'mykey': 'myvalue', 'myotherkey': 10}

This may look a little more complex, but it does the same thing the first three lines of our example above did.

Why is all of this important? It lets us keep all of our values grouped under a single variable. In the Django template language, the Context holds a dictionary of all the values we are going to make available to our template. When Django passes the dictionary to the template, the keys are what the placeholders are going to work with to be replaced with their values.

How invalid variables are handled

If you try to use a variable in your template that has not been made available to the context object, you will not get an error. The template system simply ignores it and keeps on going. This was a design decision by the Django developers to prevent a missing data item from "breaking" an application.

If you have an error with a template tag, however, you will get an error.