Using the template system

A Django project can be configured with one or several template engines (or even zero if you don't use templates). Django ships with a built-in backend for its own template system-the Django Template Language (DTL). Django 1.8 also includes support for the popular alternative Jinja2 (for more information visit http://jinja.pocoo.org/). If you don't have a pressing reason to choose another backend, you should use the DTL-especially if you're writing a pluggable application and you intend to distribute templates. Django's contrib apps that include templates, like django.contrib.admin, use the DTL. All of the examples in this chapter will use the DTL. For more advanced template topics, including configuring third-party template engines, see Chapter 8, Advanced Templates. Before we go about implementing Django templates in your view, lets first dig inside the DTL a little so you can see how it works. Here is the most basic way you can use Django's template system in Python code:

  1. Create a Template object by providing the raw template code as a string.
  2. Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.

In code, here's what that looks like:

>>> from django import template 
>>> t = template.Template('My name is {{ name }}.') 
>>> c = template.Context({'name': 'Nige'}) 
>>> print (t.render(c)) 
My name is Nige. 
>>> c = template.Context({'name': 'Barry'}) 
>>> print (t.render(c)) 
My name is Barry. 

The following sections describe each step in much more detail.

Creating template objects

The easiest way to create a Template object is to instantiate it directly. The Template class lives in the django.template module, and the constructor takes one argument, the raw template code. Let's dip into the Python interactive interpreter to see how this works in code. From the mysite project directory you created in Chapter 1, Introduction to Django and Getting Started, type python manage.py shell to start the interactive interpreter.

Let's go through some template system basics:

>>> from django.template import Template 
>>> t = Template('My name is {{ name }}.') 
>>> print (t) 

If you're following along interactively, you'll see something like this:

<django.template.base.Template object at 0x030396B0> 

That 0x030396B0 will be different every time, and it isn't relevant; it's a Python thing (the Python "identity" of the Template object, if you must know).

When you create a Template object, the template system compiles the raw template code into an internal, optimized form, ready for rendering. But if your template code includes any syntax errors, the call to Template() will cause a TemplateSyntaxError exception:

>>> from django.template import Template 
>>> t = Template('{% notatag %}') 
Traceback (most recent call last): 
  File "", line 1, in ? 
  ... 
django.template.base.TemplateSyntaxError: Invalid block tag: 'notatag' 

The term "block tag" here refers to {% notatag %}. "Block tag" and "template tag" are synonymous. The system raises a TemplateSyntaxError exception for any of the following cases:

  • Invalid tags
  • Invalid arguments to valid tags
  • Invalid filters
  • Invalid arguments to valid filters
  • Invalid template syntax
  • Unclosed tags (for tags that require closing tags)

Rendering a template

Once you have a Template object, you can pass it data by giving it a context. A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags. A context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values.

Call the Template object's render() method with the context to fill the template:

>>> from django.template import Context, Template 
>>> t = Template('My name is {{ name }}.') 
>>> c = Context({'name': 'Stephane'}) 
>>> t.render(c) 
'My name is Stephane.' 

Note

A special Python prompt

If you've used Python before, you may be wondering why we're running python manage.py shell instead of just python (or python3). Both commands will start the interactive interpreter, but the manage.py shell command has one key difference: before starting the interpreter, it tells Django which settings file to use. Many parts of Django, including the template system, rely on your settings, and you won't be able to use them unless the framework knows which settings to use.

If you're curious, here's how it works behind the scenes. Django looks for an environment variable called DJANGO_SETTINGS_MODULE, which should be set to the import path of your settings.py. For example, DJANGO_SETTINGS_MODULE might be set to 'mysite.settings', assuming mysite is on your Python path.

When you run python manage.py shell, the command takes care of setting DJANGO_SETTINGS_MODULE for you. You will need to use python manage.py shell in these examples or Django will throw an exception.

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

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