Return to site

Templates For Pages – Design 6 0 3 0

broken image


Impressive Design Projects Made Easy. Created for the home office, The Print Shop is ready to help you make some design magic. Packed with tons of easy-to-use text, photo editing, and page layout tools, it also has over 4,800 pre-made design templates and over 193,000 pieces of clip art and photos at your disposal to create impressive projects to suit any taste. The 'Design' interface also permits you to change the layout, theme clip, and theme image (from many predefined templates). With the help of the 'Element Preview' window, the changes can be seen.

Being a web framework, Django needs a convenient way to generate HTMLdynamically. The most common approach relies on templates. A template containsthe static parts of the desired HTML output as well as some special syntaxdescribing how dynamic content will be inserted. For a hands-on example ofcreating HTML pages with templates, see Tutorial 3.

A Django project can be configured with one or several template engines (oreven zero if you don't use templates). Django ships built-in backends for itsown template system, creatively called the Django template language (DTL), andfor the popular alternative Jinja2. Backends for other template languages maybe available from third-parties. You can also write your own custom backend,see Custom template backend

Django defines a standard API for loading and rendering templates regardlessof the backend. Loading consists of finding the template for a given identifierand preprocessing it, usually compiling it to an in-memory representation.Rendering means interpolating the template with context data and returning theresulting string.

The Django template language is Django's owntemplate system. Until Django 1.8 it was the only built-in option available.It's a good template library even though it's fairly opinionated and sports afew idiosyncrasies. If you don't have a pressing reason to choose anotherbackend, you should use the DTL, especially if you're writing a pluggableapplication and you intend to distribute templates. Django's contrib apps thatinclude templates, like django.contrib.admin,use the DTL.

For historical reasons, both the generic support for template engines and theimplementation of the Django template language live in the django.templatenamespace.

Warning

The template system isn't safe against untrusted template authors. Forexample, a site shouldn't allow its users to provide their own templates,since template authors can do things like perform XSS attacks and accessproperties of template variables that may contain sensitive information.

The Django template language¶

Syntax¶

About this section

This is an overview of the Django template language's syntax. For detailssee the language syntax reference.

A Django template is a text document or a Python string marked-up using theDjango template language. Some constructs are recognized and interpreted by thetemplate engine. The main ones are variables and tags.

A template is rendered with a context. Rendering replaces variables with theirvalues, which are looked up in the context, and executes tags. Everything elseis output as is.

The syntax of the Django template language involves four constructs.

Variables¶

A variable outputs a value from the context, which is a dict-like objectmapping keys to values.

Variables are surrounded by {{ and }} like this:

With a context of {'first_name':'John','last_name':'Doe'}, this templaterenders to:

Dictionary lookup, attribute lookup and list-index lookups are implemented witha dot notation:

If a variable resolves to a callable, the template system will call it with noarguments and use its result instead of the callable.

Tags¶

Tags provide arbitrary logic in the rendering process.

This definition is deliberately vague. For example, a tag can output content,serve as a control structure e.g. an 'if' statement or a 'for' loop, grabcontent from a database, or even enable access to other template tags.

Tags are surrounded by {% and %} like this:

Most tags accept arguments:

Some tags require beginning and ending tags:

A reference of built-in tags isavailable as well as instructions for writing custom tags.

Filters¶

Filters transform the values of variables and tag arguments.

They look like this:

With a context of {'django':'thewebframeworkforperfectionistswithdeadlines'}, this template renders to:

Some filters take an argument:

A reference of built-in filters isavailable as well as instructions for writing custom filters.

Comments¶

Comments look like this:

A {%comment%} tag provides multi-line comments.

Components¶

About this section

This is an overview of the Django template language's APIs. For detailssee the API reference.

Engine¶

django.template.Engine encapsulates an instance of the Djangotemplate system. The main reason for instantiating anEngine directly is to use the Django templatelanguage outside of a Django project.

django.template.backends.django.DjangoTemplates is a thin wrapperadapting django.template.Engine to Django's template backend API.

Template¶

django.template.Template represents a compiled template. Templates areobtained with Engine.get_template() or Engine.from_string().

Likewise django.template.backends.django.Template is a thin wrapperadapting django.template.Template to the common template API.

Context¶

django.template.Context holds some metadata in addition to the contextdata. It is passed to Template.render() for rendering a template.

django.template.RequestContext is a subclass ofContext that stores the currentHttpRequest and runs template context processors.

The common API doesn't have an equivalent concept. Context data is passed in aplain dict and the current HttpRequest is passedseparately if needed.

Templates For Pages – Design 6 0 3 0 M

Loaders¶

Template loaders are responsible for locating templates, loading them, andreturning Template objects.

Django provides several built-in template loadersand supports custom template loaders.

Context processors¶

Context processors are functions that receive the currentHttpRequest as an argument and return a dict ofdata to be added to the rendering context.

Their main use is to add common data shared by all templates to the contextwithout repeating code in every view.

Django provides many built-in context processors,and you can implement your own additional context processors, too.

Support for template engines¶

Configuration¶

Templates engines are configured with the TEMPLATES setting. It's alist of configurations, one for each engine. The default value is empty. Thesettings.py generated by the startproject command defines amore useful value:

BACKEND is a dotted Python path to a templateengine class implementing Django's template backend API. The built-in backendsare django.template.backends.django.DjangoTemplates anddjango.template.backends.jinja2.Jinja2.

Since most engines load templates from files, the top-level configuration foreach engine contains two common settings:

  • DIRS defines a list of directories where theengine should look for template source files, in search order.
  • APP_DIRS tells whether the engine shouldlook for templates inside installed applications. Each backend defines aconventional name for the subdirectory inside applications where itstemplates should be stored.

While uncommon, it's possible to configure several instances of the samebackend with different options. In that case you should define a uniqueNAME for each engine.

OPTIONS contains backend-specific settings.

Usage¶

The django.template.loader module defines two functions to load templates.

get_template(template_name, using=None

This function loads the template with the given name and returns aTemplate object.

The exact type of the return value depends on the backend that loaded thetemplate. Each backend has its own Template class.

get_template() tries each template engine in order until one succeeds.If the template cannot be found, it raisesTemplateDoesNotExist. If the template is found butcontains invalid syntax, it raisesTemplateSyntaxError.

How templates are searched and loaded depends on each engine's backend andconfiguration.

Snagit 2020 1 2 release. If you want to restrict the search to a particular template engine, passthe engine's NAME in the using argument.

select_template(template_name_list, using=None

select_template() is just like get_template(), except it takes alist of template names. It tries each name in order and returns the firsttemplate that exists.

If loading a template fails, the following two exceptions, defined indjango.template, may be raised:

exception TemplateDoesNotExist(msg, tried=None, backend=None, chain=None

This exception is raised when a template cannot be found. It accepts thefollowing optional arguments for populating the template postmortem on the debug page:

backend
The template backend instance from which the exception originated.
tried
A list of sources that were tried when finding the template. This isformatted as a list of tuples containing (origin,status), whereorigin is an origin-like object andstatus is a string with the reason the template wasn't found.
chain
A list of intermediate TemplateDoesNotExistexceptions raised when trying to load a template. This is used byfunctions, such as get_template(), thattry to load a given template from multiple engines.
Design
exception TemplateSyntaxError(msg

This exception is raised when a template was found but contains errors.

Template objects returned by get_template() and select_template()must provide a render() method with the following signature:

Template.render(context=None, request=None

Renders this template with a given context.

If context is provided, it must be a dict. If it isn'tprovided, the engine will render the template with an empty context.

If request is provided, it must be an HttpRequest.Then the engine must make it, as well as the CSRF token, available in thetemplate. How this is achieved is up to each backend.

Here's an example of the search algorithm. For this example theTEMPLATES setting is:

If you call get_template('story_detail.html'), here are the files Djangowill look for, in order:

  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)

If you call select_template(['story_253_detail.html','story_detail.html']),here's what Django will look for:

  • /home/html/example.com/story_253_detail.html ('django' engine)
  • /home/html/default/story_253_detail.html ('django' engine)
  • /home/html/jinja2/story_253_detail.html ('jinja2' engine)
  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)

When Django finds a template that exists, it stops looking.

Tip

Templates For Pages – Design 6 0 3 0 1n 0 3

You can use select_template() for flexibletemplate loading. For example, if you've written a news story and wantsome stories to have custom templates, use something likeselect_template(['story_%s_detail.html'%story.id,'story_detail.html']). That'll allow you to use a custom template for anindividual story, with a fallback template for stories that don't havecustom templates.

It's possible – and preferable – to organize templates in subdirectoriesinside each directory containing templates. The convention is to make asubdirectory for each Django app, with subdirectories within thosesubdirectories as needed.

Do this for your own sanity. Storing all templates in the root level of asingle directory gets messy.

To load a template that's within a subdirectory, use a slash, like so:

Using the same TEMPLATES option as above, this will attempt to loadthe following templates:

  • /home/html/example.com/news/story_detail.html ('django' engine)
  • /home/html/default/news/story_detail.html ('django' engine)
  • /home/html/jinja2/news/story_detail.html ('jinja2' engine)

In addition, to cut down on the repetitive nature of loading and renderingtemplates, Django provides a shortcut function which automates the process.

render_to_string(template_name, context=None, request=None, using=None

render_to_string() loads a template like get_template() andcalls its render() method immediately. It takes the followingarguments.

template_name
The name of the template to load and render. If it's a list of templatenames, Django uses select_template() instead ofget_template() to find the template.
context
A dict to be used as the template's context for rendering.
request
An optional HttpRequest that will be availableduring the template's rendering process.
using
An optional template engine NAME. Thesearch for the template will be restricted to that engine.

Usage example:

See also the render() shortcut which callsrender_to_string() and feeds the result into anHttpResponse suitable for returning from a view.

Finally, you can use configured engines directly:

engines

Template engines are available in django.template.engines:

The lookup key — 'django' in this example — is the engine'sNAME.

Built-in backends¶

class DjangoTemplates

Set BACKEND to'django.template.backends.django.DjangoTemplates' to configure a Djangotemplate engine.

When APP_DIRS is True, DjangoTemplatesengines look for templates in the templates subdirectory of installedapplications. This generic name was kept for backwards-compatibility.

DjangoTemplates engines accept the following OPTIONS:

  • 'autoescape': a boolean that controls whether HTML autoescaping isenabled.

    It defaults to True.

    Warning

    Only set it to False if you're rendering non-HTML templates!

  • 'context_processors': a list of dotted Python paths to callables thatare used to populate the context when a template is rendered with a request.These callables take a request object as their argument and return adict of items to be merged into the context.

    It defaults to an empty list.

    See RequestContext for more information.

  • 'debug': a boolean that turns on/off template debug mode. If it isTrue, the fancy error page will display a detailed report for anyexception raised during template rendering. This report contains therelevant snippet of the template with the appropriate line highlighted.

    It defaults to the value of the DEBUG setting.

  • 'loaders': a list of dotted Python paths to template loader classes.Each Loader class knows how to import templates from a particularsource. Optionally, a tuple can be used instead of a string. The first itemin the tuple should be the Loader class name, and subsequent items arepassed to the Loader during initialization.

    The default depends on the values of DIRS andAPP_DIRS.

    See Loader types for details.

  • 'string_if_invalid': the output, as a string, that the template systemshould use for invalid (e.g. misspelled) variables.

    It defaults to an empty string.

    See How invalid variables are handled for details.

  • 'file_charset': the charset used to read template files on disk.

    It defaults to 'utf-8'.

  • 'libraries': A dictionary of labels and dotted Python paths of templatetag modules to register with the template engine. This can be used to addnew libraries or provide alternate labels for existing ones. For example:

    Libraries can be loaded by passing the corresponding dictionary key tothe {%load%} tag.

  • 'builtins': A list of dotted Python paths of template tag modules toadd to built-ins. For example:

    Tags and filters from built-in libraries can be used without first callingthe {%load%} tag.

class Jinja2

Requires Jinja2 to be installed:

/

Set BACKEND to'django.template.backends.jinja2.Jinja2' to configure a Jinja2 engine.

Templates For Pages – Design 6 0 3 0
exception TemplateSyntaxError(msg

This exception is raised when a template was found but contains errors.

Template objects returned by get_template() and select_template()must provide a render() method with the following signature:

Template.render(context=None, request=None

Renders this template with a given context.

If context is provided, it must be a dict. If it isn'tprovided, the engine will render the template with an empty context.

If request is provided, it must be an HttpRequest.Then the engine must make it, as well as the CSRF token, available in thetemplate. How this is achieved is up to each backend.

Here's an example of the search algorithm. For this example theTEMPLATES setting is:

If you call get_template('story_detail.html'), here are the files Djangowill look for, in order:

  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)

If you call select_template(['story_253_detail.html','story_detail.html']),here's what Django will look for:

  • /home/html/example.com/story_253_detail.html ('django' engine)
  • /home/html/default/story_253_detail.html ('django' engine)
  • /home/html/jinja2/story_253_detail.html ('jinja2' engine)
  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)

When Django finds a template that exists, it stops looking.

Tip

Templates For Pages – Design 6 0 3 0 1n 0 3

You can use select_template() for flexibletemplate loading. For example, if you've written a news story and wantsome stories to have custom templates, use something likeselect_template(['story_%s_detail.html'%story.id,'story_detail.html']). That'll allow you to use a custom template for anindividual story, with a fallback template for stories that don't havecustom templates.

It's possible – and preferable – to organize templates in subdirectoriesinside each directory containing templates. The convention is to make asubdirectory for each Django app, with subdirectories within thosesubdirectories as needed.

Do this for your own sanity. Storing all templates in the root level of asingle directory gets messy.

To load a template that's within a subdirectory, use a slash, like so:

Using the same TEMPLATES option as above, this will attempt to loadthe following templates:

  • /home/html/example.com/news/story_detail.html ('django' engine)
  • /home/html/default/news/story_detail.html ('django' engine)
  • /home/html/jinja2/news/story_detail.html ('jinja2' engine)

In addition, to cut down on the repetitive nature of loading and renderingtemplates, Django provides a shortcut function which automates the process.

render_to_string(template_name, context=None, request=None, using=None

render_to_string() loads a template like get_template() andcalls its render() method immediately. It takes the followingarguments.

template_name
The name of the template to load and render. If it's a list of templatenames, Django uses select_template() instead ofget_template() to find the template.
context
A dict to be used as the template's context for rendering.
request
An optional HttpRequest that will be availableduring the template's rendering process.
using
An optional template engine NAME. Thesearch for the template will be restricted to that engine.

Usage example:

See also the render() shortcut which callsrender_to_string() and feeds the result into anHttpResponse suitable for returning from a view.

Finally, you can use configured engines directly:

engines

Template engines are available in django.template.engines:

The lookup key — 'django' in this example — is the engine'sNAME.

Built-in backends¶

class DjangoTemplates

Set BACKEND to'django.template.backends.django.DjangoTemplates' to configure a Djangotemplate engine.

When APP_DIRS is True, DjangoTemplatesengines look for templates in the templates subdirectory of installedapplications. This generic name was kept for backwards-compatibility.

DjangoTemplates engines accept the following OPTIONS:

  • 'autoescape': a boolean that controls whether HTML autoescaping isenabled.

    It defaults to True.

    Warning

    Only set it to False if you're rendering non-HTML templates!

  • 'context_processors': a list of dotted Python paths to callables thatare used to populate the context when a template is rendered with a request.These callables take a request object as their argument and return adict of items to be merged into the context.

    It defaults to an empty list.

    See RequestContext for more information.

  • 'debug': a boolean that turns on/off template debug mode. If it isTrue, the fancy error page will display a detailed report for anyexception raised during template rendering. This report contains therelevant snippet of the template with the appropriate line highlighted.

    It defaults to the value of the DEBUG setting.

  • 'loaders': a list of dotted Python paths to template loader classes.Each Loader class knows how to import templates from a particularsource. Optionally, a tuple can be used instead of a string. The first itemin the tuple should be the Loader class name, and subsequent items arepassed to the Loader during initialization.

    The default depends on the values of DIRS andAPP_DIRS.

    See Loader types for details.

  • 'string_if_invalid': the output, as a string, that the template systemshould use for invalid (e.g. misspelled) variables.

    It defaults to an empty string.

    See How invalid variables are handled for details.

  • 'file_charset': the charset used to read template files on disk.

    It defaults to 'utf-8'.

  • 'libraries': A dictionary of labels and dotted Python paths of templatetag modules to register with the template engine. This can be used to addnew libraries or provide alternate labels for existing ones. For example:

    Libraries can be loaded by passing the corresponding dictionary key tothe {%load%} tag.

  • 'builtins': A list of dotted Python paths of template tag modules toadd to built-ins. For example:

    Tags and filters from built-in libraries can be used without first callingthe {%load%} tag.

class Jinja2

Requires Jinja2 to be installed:

/

Set BACKEND to'django.template.backends.jinja2.Jinja2' to configure a Jinja2 engine.

When APP_DIRS is True, Jinja2 engineslook for templates in the jinja2 subdirectory of installed applications. Graphicconverter 10 6 3 download free.

The most important entry in OPTIONS is'environment'. It's a dotted Python path to a callable returning a Jinja2environment. It defaults to 'jinja2.Environment'. Django invokes thatcallable and passes other options as keyword arguments. Furthermore, Djangoadds defaults that differ from Jinja2's for a few options:

  • 'autoescape': True
  • 'loader': a loader configured for DIRS andAPP_DIRS
  • 'auto_reload': settings.DEBUG
  • 'undefined': DebugUndefinedifsettings.DEBUGelseUndefined

Jinja2 engines also accept the following OPTIONS: Sketch 3 6 1.

  • 'context_processors': a list of dotted Python paths to callables thatare used to populate the context when a template is rendered with a request.These callables take a request object as their argument and return adict of items to be merged into the context.

    It defaults to an empty list.

    Using context processors with Jinja2 templates is discouraged.

    Context processors are useful with Django templates because Django templatesdon't support calling functions with arguments. Since Jinja2 doesn't havethat limitation, it's recommended to put the function that you would use as acontext processor in the global variables available to the template usingjinja2.Environment as described below. You can then call that function inthe template:

    Some Django templates context processors return a fixed value. For Jinja2templates, this layer of indirection isn't necessary since you can addconstants directly in jinja2.Environment.

    The original use case for adding context processors for Jinja2 involved:

    • Making an expensive computation that depends on the request.
    • Needing the result in every template.
    • Using the result multiple times in each template.

    Unless all of these conditions are met, passing a function to the template ismore in line with the design of Jinja2.

The default configuration is purposefully kept to a minimum. If a template isrendered with a request (e.g. when using render()),the Jinja2 backend adds the globals request, csrf_input, andcsrf_token to the context. Apart from that, this backend doesn't create aDjango-flavored environment. It doesn't know about Django filters and tags.In order to use Django-specific APIs, you must configure them into theenvironment.

For example, you can create myproject/jinja2.py with this content:

Templates For Pages – Design 6 0 3 0 5f 0 7

and set the 'environment' option to 'myproject.jinja2.environment'.

Then you could use the following constructs in Jinja2 templates:

Templates For Pages – Design 6 0 3 0 1

The concepts of tags and filters exist both in the Django template languageand in Jinja2 but they're used differently. Since Jinja2 supports passingarguments to callables in templates, many features that require a template tagor filter in Django templates can be achieved by calling a function in Jinja2templates, as shown in the example above. Jinja2's global namespace removes theneed for template context processors. The Django template language doesn't havean equivalent of Jinja2 tests.





broken image