The output is sent to the browser

Một phần của tài liệu Django 1 0 template development (Trang 32 - 37)

The rendered template is packaged up with formatting that is needed by the browser to understand how to accept and display the page. By adding this formatting, the string has been turned into an HTTP response that is sent back to the browser.

In this example, the response is HTML, but it doesn't have to be. It could also be plain text, XML, JavaScript, CSV, PDF, and so on. Part of the formatting of the HTTP response tells the browser what the MIME type of the response is, and it tells the browser what kind of data to expect.

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.

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.

TagsTemplate 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!

Chapter 1

[ 17 ] {% 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.

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.

Chapter 1

[ 19 ]

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.

Creating our demo application

Throughout the book, we're going to work with the same example site so that we don't have to set up a new project for every chapter. This project will explore all the concepts throughout the book.

Rather than work with the clichéd example of a blog, we'll work with example applications that you'd find in a typical corporate website, such as news and press releases. If you've ever worked a corporate job, you've probably done something like this (and if you haven't, stick it on your resume when you're done!).

The specific configuration directives (project file system locations, database names/passwords, and so on) are given to maintain consistency throughout the book. Feel free to change them to suit your specific needs, but be sure your settings.py file matches your setup. If you decide to put the project in a different directory on the file system than what is used here, make sure to change your code appropriately when doing the examples in this book. (Hint: It's probably easier to follow along with these values if at all possible!)

Prerequisite #1: Install and test the Django framework

Installing the Django framework is thoroughly covered in the documentation on the DjangoProject.com site. If you have trouble, you can try posting a message to the Django-Users|Google Group (http://groups-beta.google.com/group/

django-users).

If you can start a Python shell and successfully run the command importdjango, you should be good to continue.

At the time of this writing, the latest release of Django is 1.0, so that's what we will be using here.

Prerequisite #2: Create a new database

For purposes of this book, it doesn't matter what database engine you use as long as Django supports it (for example, MySQL, PostgreSQL, SQLite, and so on). If you don't have MySQL or PostgreSQL installed, SQLite is probably the easiest choice to work with as it requires zero administration to set up and use.

If you are using MySQL or PostgreSQL, following the instructions of your specific database engine, perform the following tasks. (If you are using SQLite, you don't have to do this.)

1. Create a database called mycompany.

Một phần của tài liệu Django 1 0 template development (Trang 32 - 37)

Tải bản đầy đủ (PDF)

(272 trang)