diff options
Diffstat (limited to 'parts/django/docs/ref/templates')
-rw-r--r-- | parts/django/docs/ref/templates/api.txt | 815 | ||||
-rw-r--r-- | parts/django/docs/ref/templates/builtins.txt | 2107 | ||||
-rw-r--r-- | parts/django/docs/ref/templates/index.txt | 19 |
3 files changed, 0 insertions, 2941 deletions
diff --git a/parts/django/docs/ref/templates/api.txt b/parts/django/docs/ref/templates/api.txt deleted file mode 100644 index 1111869..0000000 --- a/parts/django/docs/ref/templates/api.txt +++ /dev/null @@ -1,815 +0,0 @@ -==================================================== -The Django template language: For Python programmers -==================================================== - -This document explains the Django template system from a technical -perspective -- how it works and how to extend it. If you're just looking for -reference on the language syntax, see :doc:`/topics/templates`. - -If you're looking to use the Django template system as part of another -application -- i.e., without the rest of the framework -- make sure to read -the `configuration`_ section later in this document. - -.. _configuration: `configuring the template system in standalone mode`_ - -Basics -====== - -A **template** is a text document, or a normal Python string, that is marked-up -using the Django template language. A template can contain **block tags** or -**variables**. - -A **block tag** is a symbol within a template that does something. - -This definition is deliberately vague. For example, a block tag can output -content, serve as a control structure (an "if" statement or "for" loop), grab -content from a database or enable access to other template tags. - -Block tags are surrounded by ``"{%"`` and ``"%}"``. - -Example template with block tags: - -.. code-block:: html+django - - {% 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 ``"}}"``. - -Example template with variables: - -.. code-block:: html+django - - My first name is {{ first_name }}. My last name is {{ last_name }}. - -A **context** is a "variable name" -> "variable value" mapping that is passed -to a template. - -A template **renders** a context by replacing the variable "holes" with values -from the context and executing all block tags. - -Using the template system -========================= - -.. class:: django.template.Template - -Using the template system in Python is a two-step process: - - * First, you compile the raw template code into a ``Template`` object. - * Then, you call the ``render()`` method of the ``Template`` object with a - given context. - -Compiling a string ------------------- - -The easiest way to create a ``Template`` object is by instantiating it -directly. The class lives at :class:`django.template.Template`. The constructor -takes one argument -- the raw template code:: - - >>> from django.template import Template - >>> t = Template("My name is {{ my_name }}.") - >>> print t - <django.template.Template instance> - -.. admonition:: Behind the scenes - - The system only parses your raw template code once -- when you create the - ``Template`` object. From then on, it's stored internally as a "node" - structure for performance. - - Even the parsing itself is quite fast. Most of the parsing happens via a - single call to a single, short, regular expression. - -Rendering a context -------------------- - -.. method:: render(context) - -Once you have a compiled ``Template`` object, you can render a context -- or -multiple contexts -- with it. The ``Context`` class lives at -:class:`django.template.Context`, and the constructor takes two (optional) -arguments: - - * A dictionary mapping variable names to variable values. - - * The name of the current application. This application name is used - to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`. - If you're not using namespaced URLs, you can ignore this argument. - -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 {{ my_name }}.") - - >>> c = Context({"my_name": "Adrian"}) - >>> t.render(c) - "My name is Adrian." - - >>> c = Context({"my_name": "Dolores"}) - >>> t.render(c) - "My name is Dolores." - -Variable names must consist of any letter (A-Z), any digit (0-9), an underscore -or a dot. - -Dots have a special meaning in template rendering. A dot in a variable name -signifies **lookup**. Specifically, when the template system encounters a dot -in a variable name, it tries the following lookups, in this order: - - * Dictionary lookup. Example: ``foo["bar"]`` - * Attribute lookup. Example: ``foo.bar`` - * Method call. Example: ``foo.bar()`` - * List-index lookup. Example: ``foo[bar]`` - -The template system uses the first lookup type that works. It's short-circuit -logic. - -Here are a few examples:: - - >>> from django.template import Context, Template - >>> t = Template("My name is {{ person.first_name }}.") - >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}} - >>> t.render(Context(d)) - "My name is Joe." - - >>> class PersonClass: pass - >>> p = PersonClass() - >>> p.first_name = "Ron" - >>> p.last_name = "Nasty" - >>> t.render(Context({"person": p})) - "My name is Ron." - - >>> class PersonClass2: - ... def first_name(self): - ... return "Samantha" - >>> p = PersonClass2() - >>> t.render(Context({"person": p})) - "My name is Samantha." - - >>> t = Template("The first stooge in the list is {{ stooges.0 }}.") - >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]}) - >>> t.render(c) - "The first stooge in the list is Larry." - -Method lookups are slightly more complex than the other lookup types. Here are -some things to keep in mind: - - * If, during the method lookup, a method raises an exception, the exception - will be propagated, unless the exception has an attribute - ``silent_variable_failure`` whose value is ``True``. If the exception - *does* have a ``silent_variable_failure`` attribute, the variable will - render as an empty string. Example:: - - >>> t = Template("My name is {{ person.first_name }}.") - >>> class PersonClass3: - ... def first_name(self): - ... raise AssertionError, "foo" - >>> p = PersonClass3() - >>> t.render(Context({"person": p})) - Traceback (most recent call last): - ... - AssertionError: foo - - >>> class SilentAssertionError(Exception): - ... silent_variable_failure = True - >>> class PersonClass4: - ... def first_name(self): - ... raise SilentAssertionError - >>> p = PersonClass4() - >>> t.render(Context({"person": p})) - "My name is ." - - Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the - base class for all Django database API ``DoesNotExist`` exceptions, has - ``silent_variable_failure = True``. So if you're using Django templates - with Django model objects, any ``DoesNotExist`` exception will fail - silently. - - * A method call will only work if the method has no required arguments. - Otherwise, the system will move to the next lookup type (list-index - lookup). - - * Obviously, some methods have side effects, and it'd be either foolish or - a security hole to allow the template system to access them. - - A good example is the :meth:`~django.db.models.Model.delete` method on - each Django model object. The template system shouldn't be allowed to do - something like this:: - - I will now delete this valuable data. {{ data.delete }} - - To prevent this, set a function attribute ``alters_data`` on the method. - The template system won't execute a method if the method has - ``alters_data=True`` set. The dynamically-generated - :meth:`~django.db.models.Model.delete` and - :meth:`~django.db.models.Model.save` methods on Django model objects get - ``alters_data=True`` automatically. Example:: - - def sensitive_function(self): - self.database_record.delete() - sensitive_function.alters_data = True - -.. _invalid-template-variables: - -How invalid variables are handled -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Generally, if a variable doesn't exist, the template system inserts the -value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set to -``''`` (the empty string) by default. - -Filters that are applied to an invalid variable will only be applied if -:setting:`TEMPLATE_STRING_IF_INVALID` is set to ``''`` (the empty string). If -:setting:`TEMPLATE_STRING_IF_INVALID` is set to any other value, variable -filters will be ignored. - -This behavior is slightly different for the ``if``, ``for`` and ``regroup`` -template tags. If an invalid variable is provided to one of these template -tags, the variable will be interpreted as ``None``. Filters are always -applied to invalid variables within these template tags. - -If :setting:`TEMPLATE_STRING_IF_INVALID` contains a ``'%s'``, the format marker will -be replaced with the name of the invalid variable. - -.. admonition:: For debug purposes only! - - While :setting:`TEMPLATE_STRING_IF_INVALID` can be a useful debugging tool, - it is a bad idea to turn it on as a 'development default'. - - Many templates, including those in the Admin site, rely upon the - silence of the template system when a non-existent variable is - encountered. If you assign a value other than ``''`` to - :setting:`TEMPLATE_STRING_IF_INVALID`, you will experience rendering - problems with these templates and sites. - - Generally, :setting:`TEMPLATE_STRING_IF_INVALID` should only be enabled - in order to debug a specific template problem, then cleared - once debugging is complete. - -Playing with Context objects ----------------------------- - -.. class:: django.template.Context - -Most of the time, you'll instantiate ``Context`` objects by passing in a -fully-populated dictionary to ``Context()``. But you can add and delete items -from a ``Context`` object once it's been instantiated, too, using standard -dictionary syntax:: - - >>> c = Context({"foo": "bar"}) - >>> c['foo'] - 'bar' - >>> del c['foo'] - >>> c['foo'] - '' - >>> c['newvariable'] = 'hello' - >>> c['newvariable'] - 'hello' - -.. method:: pop() -.. method:: push() -.. exception:: django.template.ContextPopException - -A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it. -If you ``pop()`` too much, it'll raise -``django.template.ContextPopException``:: - - >>> c = Context() - >>> c['foo'] = 'first level' - >>> c.push() - >>> c['foo'] = 'second level' - >>> c['foo'] - 'second level' - >>> c.pop() - >>> c['foo'] - 'first level' - >>> c['foo'] = 'overwritten' - >>> c['foo'] - 'overwritten' - >>> c.pop() - Traceback (most recent call last): - ... - django.template.ContextPopException - -.. method:: update(other_dict) - -In addition to ``push()`` and ``pop()``, the ``Context`` -object also defines an ``update()`` method. This works like ``push()`` -but takes a dictionary as an argument and pushes that dictionary onto -the stack instead of an empty one. - - >>> c = Context() - >>> c['foo'] = 'first level' - >>> c.update({'foo': 'updated'}) - {'foo': 'updated'} - >>> c['foo'] - 'updated' - >>> c.pop() - {'foo': 'updated'} - >>> c['foo'] - 'first level' - -Using a ``Context`` as a stack comes in handy in some custom template tags, as -you'll see below. - -.. _subclassing-context-requestcontext: - -Subclassing Context: RequestContext ------------------------------------ - -Django comes with a special ``Context`` class, -``django.template.RequestContext``, that acts slightly differently than the -normal ``django.template.Context``. The first difference is that it takes an -:class:`~django.http.HttpRequest` as its first argument. For example:: - - c = RequestContext(request, { - 'foo': 'bar', - }) - -The second difference is that it automatically populates the context with a few -variables, according to your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. - -The :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting is a tuple of callables -- -called **context processors** -- that take a request object as their argument -and return a dictionary of items to be merged into the context. By default, -:setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to:: - - ("django.contrib.auth.context_processors.auth", - "django.core.context_processors.debug", - "django.core.context_processors.i18n", - "django.core.context_processors.media", - "django.contrib.messages.context_processors.messages") - -.. versionadded:: 1.2 - In addition to these, ``RequestContext`` always uses - ``django.core.context_processors.csrf``. This is a security - related context processor required by the admin and other contrib apps, and, - in case of accidental misconfiguration, it is deliberately hardcoded in and - cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. - -.. versionadded:: 1.2 - The ``'messages'`` context processor was added. For more information, see - the :doc:`messages documentation </ref/contrib/messages>`. - -.. versionchanged:: 1.2 - The auth context processor was moved in this release from its old location - ``django.core.context_processors.auth`` to - ``django.contrib.auth.context_processors.auth``. - -Each processor is applied in order. That means, if one processor adds a -variable to the context and a second processor adds a variable with the same -name, the second will override the first. The default processors are explained -below. - -.. admonition:: When context processors are applied - - When you use ``RequestContext``, the variables you supply directly - are added first, followed any variables supplied by context - processors. This means that a context processor may overwrite a - variable you've supplied, so take care to avoid variable names - which overlap with those supplied by your context processors. - -Also, you can give ``RequestContext`` a list of additional processors, using the -optional, third positional argument, ``processors``. In this example, the -``RequestContext`` instance gets a ``ip_address`` variable:: - - def ip_address_processor(request): - return {'ip_address': request.META['REMOTE_ADDR']} - - def some_view(request): - # ... - c = RequestContext(request, { - 'foo': 'bar', - }, [ip_address_processor]) - return HttpResponse(t.render(c)) - -.. note:: - If you're using Django's ``render_to_response()`` shortcut to populate a - template with the contents of a dictionary, your template will be passed a - ``Context`` instance by default (not a ``RequestContext``). To use a - ``RequestContext`` in your template rendering, pass an optional third - argument to ``render_to_response()``: a ``RequestContext`` - instance. Your code might look like this:: - - def some_view(request): - # ... - return render_to_response('my_template.html', - my_data_dictionary, - context_instance=RequestContext(request)) - -Here's what each of the default processors does: - -django.contrib.auth.context_processors.auth -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain these three variables: - - * ``user`` -- An ``auth.User`` instance representing the currently - logged-in user (or an ``AnonymousUser`` instance, if the client isn't - logged in). - - * ``messages`` -- A list of messages (as strings) that have been set - via the :doc:`messages framework </ref/contrib/messages>`. - - * ``perms`` -- An instance of - ``django.core.context_processors.PermWrapper``, representing the - permissions that the currently logged-in user has. - -.. versionchanged:: 1.2 - This context processor was moved in this release from - ``django.core.context_processors.auth`` to its current location. - -.. versionchanged:: 1.2 - Prior to version 1.2, the ``messages`` variable was a lazy accessor for - ``user.get_and_delete_messages()``. It has been changed to include any - messages added via the :doc:`messages framework </ref/contrib/messages>`. - -django.core.context_processors.debug -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain these two variables -- but only if your -:setting:`DEBUG` setting is set to ``True`` and the request's IP address -(``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting: - - * ``debug`` -- ``True``. You can use this in templates to test whether - you're in :setting:`DEBUG` mode. - * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries, - representing every SQL query that has happened so far during the request - and how long it took. The list is in order by query. - -django.core.context_processors.i18n -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain these two variables: - - * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting. - * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise, - the value of the :setting:`LANGUAGE_CODE` setting. - -See :doc:`/topics/i18n/index` for more. - -django.core.context_processors.media -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain a variable ``MEDIA_URL``, providing the -value of the :setting:`MEDIA_URL` setting. - -django.core.context_processors.csrf -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.2 - -This processor adds a token that is needed by the ``csrf_token`` template tag -for protection against :doc:`Cross Site Request Forgeries </ref/contrib/csrf>`. - -django.core.context_processors.request -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain a variable ``request``, which is the current -:class:`~django.http.HttpRequest`. Note that this processor is not enabled by default; -you'll have to activate it. - -django.contrib.messages.context_processors.messages -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every -``RequestContext`` will contain a single additional variable: - - * ``messages`` -- A list of messages (as strings) that have been set - via the user model (using ``user.message_set.create``) or through - the :doc:`messages framework </ref/contrib/messages>`. - -.. versionadded:: 1.2 - This template context variable was previously supplied by the ``'auth'`` - context processor. For backwards compatibility the ``'auth'`` context - processor will continue to supply the ``messages`` variable until Django - 1.4. If you use the ``messages`` variable, your project will work with - either (or both) context processors, but it is recommended to add - ``django.contrib.messages.context_processors.messages`` so your project - will be prepared for the future upgrade. - -Writing your own context processors -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A context processor has a very simple interface: It's just a Python function -that takes one argument, an :class:`~django.http.HttpRequest` object, and -returns a dictionary that gets added to the template context. Each context -processor *must* return a dictionary. - -Custom context processors can live anywhere in your code base. All Django cares -about is that your custom context processors are pointed-to by your -:setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. - -Loading templates ------------------ - -Generally, you'll store templates in files on your filesystem rather than using -the low-level ``Template`` API yourself. Save templates in a directory -specified as a **template directory**. - -Django searches for template directories in a number of places, depending on -your template-loader settings (see "Loader types" below), but the most basic -way of specifying template directories is by using the :setting:`TEMPLATE_DIRS` -setting. - -The TEMPLATE_DIRS setting -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Tell Django what your template directories are by using the -:setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a -list or tuple of strings that contain full paths to your template -directory(ies). Example:: - - TEMPLATE_DIRS = ( - "/home/html/templates/lawrence.com", - "/home/html/templates/default", - ) - -Your templates can go anywhere you want, as long as the directories and -templates are readable by the Web server. They can have any extension you want, -such as ``.html`` or ``.txt``, or they can have no extension at all. - -Note that these paths should use Unix-style forward slashes, even on Windows. - -.. _ref-templates-api-the-python-api: - -The Python API -~~~~~~~~~~~~~~ - -Django has two ways to load templates from files: - -.. function:: django.template.loader.get_template(template_name) - - ``get_template`` returns the compiled template (a ``Template`` object) for - the template with the given name. If the template doesn't exist, it raises - ``django.template.TemplateDoesNotExist``. - -.. function:: django.template.loader.select_template(template_name_list) - - ``select_template`` is just like ``get_template``, except it takes a list - of template names. Of the list, it returns the first template that exists. - -For example, if you call ``get_template('story_detail.html')`` and have the -above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for, -in order: - - * ``/home/html/templates/lawrence.com/story_detail.html`` - * ``/home/html/templates/default/story_detail.html`` - -If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``, -here's what Django will look for: - - * ``/home/html/templates/lawrence.com/story_253_detail.html`` - * ``/home/html/templates/default/story_253_detail.html`` - * ``/home/html/templates/lawrence.com/story_detail.html`` - * ``/home/html/templates/default/story_detail.html`` - -When Django finds a template that exists, it stops looking. - -.. admonition:: Tip - - You can use ``select_template()`` for super-flexible "templatability." For - example, if you've written a news story and want some stories to have - custom templates, use something like - ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``. - That'll allow you to use a custom template for an individual story, with a - fallback template for stories that don't have custom templates. - -Using subdirectories -~~~~~~~~~~~~~~~~~~~~ - -It's possible -- and preferable -- to organize templates in subdirectories of -the template directory. The convention is to make a subdirectory for each -Django app, with subdirectories within those subdirectories as needed. - -Do this for your own sanity. Storing all templates in the root level of a -single directory gets messy. - -To load a template that's within a subdirectory, just use a slash, like so:: - - get_template('news/story_detail.html') - -Using the same :setting:`TEMPLATE_DIRS` setting from above, this example -``get_template()`` call will attempt to load the following templates: - - * ``/home/html/templates/lawrence.com/news/story_detail.html`` - * ``/home/html/templates/default/news/story_detail.html`` - -.. _template-loaders: - -Loader types -~~~~~~~~~~~~ - -By default, Django uses a filesystem-based template loader, but Django comes -with a few other template loaders, which know how to load templates from other -sources. - -Some of these other loaders are disabled by default, but you can activate them -by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS` -should be a tuple of strings, where each string represents a template loader. -Here are the template loaders that come with Django: - -``django.template.loaders.filesystem.Loader`` - Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`. - This loader is enabled by default. - -``django.template.loaders.app_directories.Loader`` - Loads templates from Django apps on the filesystem. For each app in - :setting:`INSTALLED_APPS`, the loader looks for a ``templates`` - subdirectory. If the directory exists, Django looks for templates in there. - - This means you can store templates with your individual apps. This also - makes it easy to distribute Django apps with default templates. - - For example, for this setting:: - - INSTALLED_APPS = ('myproject.polls', 'myproject.music') - - ...then ``get_template('foo.html')`` will look for templates in these - directories, in this order: - - * ``/path/to/myproject/polls/templates/foo.html`` - * ``/path/to/myproject/music/templates/foo.html`` - - Note that the loader performs an optimization when it is first imported: It - caches a list of which :setting:`INSTALLED_APPS` packages have a - ``templates`` subdirectory. - - This loader is enabled by default. - -``django.template.loaders.eggs.Loader`` - Just like ``app_directories`` above, but it loads templates from Python - eggs rather than from the filesystem. - - This loader is disabled by default. - -``django.template.loaders.cached.Loader`` - By default, the templating system will read and compile your templates every - time they need to be rendered. While the Django templating system is quite - fast, the overhead from reading and compiling templates can add up. - - The cached template loader is a class-based loader that you configure with - a list of other loaders that it should wrap. The wrapped loaders are used to - locate unknown templates when they are first encountered. The cached loader - then stores the compiled ``Template`` in memory. The cached ``Template`` - instance is returned for subsequent requests to load the same template. - - For example, to enable template caching with the ``filesystem`` and - ``app_directories`` template loaders you might use the following settings:: - - TEMPLATE_LOADERS = ( - ('django.template.loaders.cached.Loader', ( - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', - )), - ) - - .. note:: - All of the built-in Django template tags are safe to use with the cached - loader, but if you're using custom template tags that come from third - party packages, or that you wrote yourself, you should ensure that the - ``Node`` implementation for each tag is thread-safe. For more - information, see - :ref:`template tag thread safety considerations<template_tag_thread_safety>`. - - This loader is disabled by default. - -Django uses the template loaders in order according to the -:setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a -match. - -The ``render_to_string`` shortcut -=================================== - -.. function:: django.template.loader.render_to_string(template_name, dictionary=None, context_instance=None) - -To cut down on the repetitive nature of loading and rendering -templates, Django provides a shortcut function which largely -automates the process: ``render_to_string()`` in -:mod:`django.template.loader`, which loads a template, renders it and -returns the resulting string:: - - from django.template.loader import render_to_string - rendered = render_to_string('my_template.html', { 'foo': 'bar' }) - -The ``render_to_string`` shortcut takes one required argument -- -``template_name``, which should be the name of the template to load -and render (or a list of template names, in which case Django will use -the first template in the list that exists) -- and two optional arguments: - - dictionary - A dictionary to be used as variables and values for the - template's context. This can also be passed as the second - positional argument. - - context_instance - An instance of ``Context`` or a subclass (e.g., an instance of - ``RequestContext``) to use as the template's context. This can - also be passed as the third positional argument. - -See also the :func:`~django.shortcuts.render_to_response()` shortcut, which -calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse` -suitable for returning directly from a view. - -Configuring the template system in standalone mode -================================================== - -.. note:: - - This section is only of interest to people trying to use the template - system as an output component in another application. If you're using the - template system as part of a Django application, nothing here applies to - you. - -Normally, Django will load all the configuration information it needs from its -own default configuration file, combined with the settings in the module given -in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're -using the template system independently of the rest of Django, the environment -variable approach isn't very convenient, because you probably want to configure -the template system in line with the rest of your application rather than -dealing with settings files and pointing to them via environment variables. - -To solve this problem, you need to use the manual configuration option described -in :ref:`settings-without-django-settings-module`. Simply import the appropriate -pieces of the templating system and then, *before* you call any of the -templating functions, call :func:`django.conf.settings.configure()` with any -settings you wish to specify. You might want to consider setting at least -:setting:`TEMPLATE_DIRS` (if you're going to use template loaders), -:setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine) -and :setting:`TEMPLATE_DEBUG`. All available settings are described in the -:doc:`settings documentation </ref/settings>`, and any setting starting with -``TEMPLATE_`` is of obvious interest. - -.. _topic-template-alternate-language: - -Using an alternative template language -====================================== - -.. versionadded:: 1.2 - -The Django ``Template`` and ``Loader`` classes implement a simple API for -loading and rendering templates. By providing some simple wrapper classes that -implement this API we can use third party template systems like `Jinja2 -<http://jinja.pocoo.org/2/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This -allows us to use third-party template libraries without giving up useful Django -features like the Django ``Context`` object and handy shortcuts like -``render_to_response()``. - -The core component of the Django templating system is the ``Template`` class. -This class has a very simple interface: it has a constructor that takes a single -positional argument specifying the template string, and a ``render()`` method -that takes a :class:`~django.template.Context` object and returns a string -containing the rendered response. - -Suppose we're using a template language that defines a ``Template`` object with -a ``render()`` method that takes a dictionary rather than a ``Context`` object. -We can write a simple wrapper that implements the Django ``Template`` interface:: - - import some_template_language - class Template(some_template_language.Template): - def render(self, context): - # flatten the Django Context into a single dictionary. - context_dict = {} - for d in context.dicts: - context_dict.update(d) - return super(Template, self).render(context_dict) - -That's all that's required to make our fictional ``Template`` class compatible -with the Django loading and rendering system! - -The next step is to write a ``Loader`` class that returns instances of our custom -template class instead of the default :class:`~django.template.Template`. Custom ``Loader`` -classes should inherit from ``django.template.loader.BaseLoader`` and override -the ``load_template_source()`` method, which takes a ``template_name`` argument, -loads the template from disk (or elsewhere), and returns a tuple: -``(template_string, template_origin)``. - -The ``load_template()`` method of the ``Loader`` class retrieves the template -string by calling ``load_template_source()``, instantiates a ``Template`` from -the template source, and returns a tuple: ``(template, template_origin)``. Since -this is the method that actually instantiates the ``Template``, we'll need to -override it to use our custom template class instead. We can inherit from the -builtin :class:`django.template.loaders.app_directories.Loader` to take advantage -of the ``load_template_source()`` method implemented there:: - - from django.template.loaders import app_directories - class Loader(app_directories.Loader): - is_usable = True - - def load_template(self, template_name, template_dirs=None): - source, origin = self.load_template_source(template_name, template_dirs) - template = Template(source) - return template, origin - -Finally, we need to modify our project settings, telling Django to use our custom -loader. Now we can write all of our templates in our alternative template -language while continuing to use the rest of the Django templating system. diff --git a/parts/django/docs/ref/templates/builtins.txt b/parts/django/docs/ref/templates/builtins.txt deleted file mode 100644 index 44bbc37..0000000 --- a/parts/django/docs/ref/templates/builtins.txt +++ /dev/null @@ -1,2107 +0,0 @@ -================================== -Built-in template tags and filters -================================== - -This document describes Django's built-in template tags and filters. It is -recommended that you use the :doc:`automatic documentation -</ref/contrib/admin/admindocs>`, if available, as this will also include -documentation for any custom tags or filters installed. - -.. _ref-templates-builtins-tags: - -Built-in tag reference ----------------------- - -.. highlightlang:: html+django - -.. templatetag:: autoescape - -autoescape -~~~~~~~~~~ - -.. versionadded:: 1.0 - -Control the current auto-escaping behavior. This tag takes either ``on`` or -``off`` as an argument and that determines whether auto-escaping is in effect -inside the block. The block is closed with an ``endautoescape`` ending tag. - -When auto-escaping is in effect, all variable content has HTML escaping applied -to it before placing the result into the output (but after any filters have -been applied). This is equivalent to manually applying the ``escape`` filter -to each variable. - -The only exceptions are variables that are already marked as "safe" from -escaping, either by the code that populated the variable, or because it has had -the ``safe`` or ``escape`` filters applied. - -Sample usage:: - - {% autoescape on %} - {{ body }} - {% endautoescape %} - -.. templatetag:: block - -block -~~~~~ - -Define a block that can be overridden by child templates. See -:ref:`Template inheritance <template-inheritance>` for more information. - -.. templatetag:: comment - -comment -~~~~~~~ - -Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` - -.. templatetag:: csrf_token - -csrf_token -~~~~~~~~~~ - -.. versionadded:: 1.1.2 - -In the Django 1.1.X series, this is a no-op tag that returns an empty string for -future compatibility purposes. In Django 1.2 and later, it is used for CSRF -protection, as described in the documentation for :doc:`Cross Site Request -Forgeries </ref/contrib/csrf>`. - -.. templatetag:: cycle - -cycle -~~~~~ - -.. versionchanged:: 1.0 - Cycle among the given strings or variables each time this tag is encountered. - -Within a loop, cycles among the given strings each time through the -loop:: - - {% for o in some_list %} - <tr class="{% cycle 'row1' 'row2' %}"> - ... - </tr> - {% endfor %} - -You can use variables, too. For example, if you have two template variables, -``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this:: - - {% for o in some_list %} - <tr class="{% cycle rowvalue1 rowvalue2 %}"> - ... - </tr> - {% endfor %} - -Yes, you can mix variables and strings:: - - {% for o in some_list %} - <tr class="{% cycle 'row1' rowvalue2 'row3' %}"> - ... - </tr> - {% endfor %} - -In some cases you might want to refer to the next value of a cycle from -outside of a loop. To do this, just give the ``{% cycle %}`` tag a name, using -"as", like this:: - - {% cycle 'row1' 'row2' as rowcolors %} - -From then on, you can insert the current value of the cycle wherever you'd like -in your template:: - - <tr class="{% cycle rowcolors %}">...</tr> - <tr class="{% cycle rowcolors %}">...</tr> - -You can use any number of values in a ``{% cycle %}`` tag, separated by spaces. -Values enclosed in single (``'``) or double quotes (``"``) are treated as -string literals, while values without quotes are treated as template variables. - -Note that the variables included in the cycle will not be escaped. -This is because template tags do not escape their content. Any HTML or -Javascript code contained in the printed variable will be rendered -as-is, which could potentially lead to security issues. - -If you need to escape the variables in the cycle, you must do so -explicitly:: - - {% filter force_escape %} - {% cycle var1 var2 var3 %} - {% endfilter %} - -For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior -old syntax from previous Django versions. You shouldn't use this in any new -projects, but for the sake of the people who are still using it, here's what it -looks like:: - - {% cycle row1,row2,row3 %} - -In this syntax, each value gets interpreted as a literal string, and there's no -way to specify variable values. Or literal commas. Or spaces. Did we mention -you shouldn't use this syntax in any new projects? - -.. templatetag:: debug - -debug -~~~~~ - -Output a whole load of debugging information, including the current context and -imported modules. - -.. templatetag:: extends - -extends -~~~~~~~ - -Signal that this template extends a parent template. - -This tag can be used in two ways: - - * ``{% extends "base.html" %}`` (with quotes) uses the literal value - ``"base.html"`` as the name of the parent template to extend. - - * ``{% extends variable %}`` uses the value of ``variable``. If the variable - evaluates to a string, Django will use that string as the name of the - parent template. If the variable evaluates to a ``Template`` object, - Django will use that object as the parent template. - -See :ref:`template-inheritance` for more information. - -.. templatetag:: filter - -filter -~~~~~~ - -Filter the contents of the variable through variable filters. - -Filters can also be piped through each other, and they can have arguments -- -just like in variable syntax. - -Sample usage:: - - {% filter force_escape|lower %} - This text will be HTML-escaped, and will appear in all lowercase. - {% endfilter %} - -.. templatetag:: firstof - -firstof -~~~~~~~ - -Outputs the first variable passed that is not False, without escaping. - -Outputs nothing if all the passed variables are False. - -Sample usage:: - - {% firstof var1 var2 var3 %} - -This is equivalent to:: - - {% if var1 %} - {{ var1|safe }} - {% else %}{% if var2 %} - {{ var2|safe }} - {% else %}{% if var3 %} - {{ var3|safe }} - {% endif %}{% endif %}{% endif %} - -You can also use a literal string as a fallback value in case all -passed variables are False:: - - {% firstof var1 var2 var3 "fallback value" %} - -Note that the variables included in the firstof tag will not be -escaped. This is because template tags do not escape their content. -Any HTML or Javascript code contained in the printed variable will be -rendered as-is, which could potentially lead to security issues. - -If you need to escape the variables in the firstof tag, you must do so -explicitly:: - - {% filter force_escape %} - {% firstof var1 var2 var3 "fallback value" %} - {% endfilter %} - -.. templatetag:: for - -for -~~~ - -Loop over each item in an array. For example, to display a list of athletes -provided in ``athlete_list``:: - - <ul> - {% for athlete in athlete_list %} - <li>{{ athlete.name }}</li> - {% endfor %} - </ul> - -You can loop over a list in reverse by using ``{% for obj in list reversed %}``. - -.. versionadded:: 1.0 - -If you need to loop over a list of lists, you can unpack the values -in each sub-list into individual variables. For example, if your context -contains a list of (x,y) coordinates called ``points``, you could use the -following to output the list of points:: - - {% for x, y in points %} - There is a point at {{ x }},{{ y }} - {% endfor %} - -This can also be useful if you need to access the items in a dictionary. -For example, if your context contained a dictionary ``data``, the following -would display the keys and values of the dictionary:: - - {% for key, value in data.items %} - {{ key }}: {{ value }} - {% endfor %} - -The for loop sets a number of variables available within the loop: - - ========================== ================================================ - Variable Description - ========================== ================================================ - ``forloop.counter`` The current iteration of the loop (1-indexed) - ``forloop.counter0`` The current iteration of the loop (0-indexed) - ``forloop.revcounter`` The number of iterations from the end of the - loop (1-indexed) - ``forloop.revcounter0`` The number of iterations from the end of the - loop (0-indexed) - ``forloop.first`` True if this is the first time through the loop - ``forloop.last`` True if this is the last time through the loop - ``forloop.parentloop`` For nested loops, this is the loop "above" the - current one - ========================== ================================================ - -for ... empty -^^^^^^^^^^^^^ - -.. versionadded:: 1.1 - -The ``for`` tag can take an optional ``{% empty %}`` clause that will be -displayed if the given array is empty or could not be found:: - - <ul> - {% for athlete in athlete_list %} - <li>{{ athlete.name }}</li> - {% empty %} - <li>Sorry, no athlete in this list!</li> - {% endfor %} - <ul> - -The above is equivalent to -- but shorter, cleaner, and possibly faster -than -- the following:: - - <ul> - {% if athlete_list %} - {% for athlete in athlete_list %} - <li>{{ athlete.name }}</li> - {% endfor %} - {% else %} - <li>Sorry, no athletes in this list.</li> - {% endif %} - </ul> - -.. templatetag:: if - -if -~~ - -The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e. -exists, is not empty, and is not a false boolean value) the contents of the -block are output:: - - {% if athlete_list %} - Number of athletes: {{ athlete_list|length }} - {% else %} - No athletes. - {% endif %} - -In the above, if ``athlete_list`` is not empty, the number of athletes will be -displayed by the ``{{ athlete_list|length }}`` variable. - -As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that -will be displayed if the test fails. - -Boolean operators -^^^^^^^^^^^^^^^^^ - -``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or -to negate a given variable:: - - {% if athlete_list and coach_list %} - Both athletes and coaches are available. - {% endif %} - - {% if not athlete_list %} - There are no athletes. - {% endif %} - - {% if athlete_list or coach_list %} - There are some athletes or some coaches. - {% endif %} - - {% if not athlete_list or coach_list %} - There are no athletes or there are some coaches (OK, so - writing English translations of boolean logic sounds - stupid; it's not our fault). - {% endif %} - - {% if athlete_list and not coach_list %} - There are some athletes and absolutely no coaches. - {% endif %} - -.. versionchanged:: 1.2 - -Use of both ``and`` and ``or`` clauses within the same tag is allowed, with -``and`` having higher precedence than ``or`` e.g.:: - - {% if athlete_list and coach_list or cheerleader_list %} - -will be interpreted like: - -.. code-block:: python - - if (athlete_list and coach_list) or cheerleader_list - -Use of actual brackets in the ``if`` tag is invalid syntax. If you need them to -indicate precedence, you should use nested ``if`` tags. - -.. versionadded:: 1.2 - - -``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``, -``<=``, ``>=`` and ``in`` which work as follows: - - -``==`` operator -^^^^^^^^^^^^^^^ - -Equality. Example:: - - {% if somevar == "x" %} - This appears if variable somevar equals the string "x" - {% endif %} - -``!=`` operator -^^^^^^^^^^^^^^^ - -Inequality. Example:: - - {% if somevar != "x" %} - This appears if variable somevar does not equal the string "x", - or if somevar is not found in the context - {% endif %} - -``<`` operator -^^^^^^^^^^^^^^ - -Less than. Example:: - - {% if somevar < 100 %} - This appears if variable somevar is less than 100. - {% endif %} - -``>`` operator -^^^^^^^^^^^^^^ - -Greater than. Example:: - - {% if somevar > 0 %} - This appears if variable somevar is greater than 0. - {% endif %} - -``<=`` operator -^^^^^^^^^^^^^^^ - -Less than or equal to. Example:: - - {% if somevar <= 100 %} - This appears if variable somevar is less than 100 or equal to 100. - {% endif %} - -``>=`` operator -^^^^^^^^^^^^^^^ - -Greater than or equal to. Example:: - - {% if somevar >= 1 %} - This appears if variable somevar is greater than 1 or equal to 1. - {% endif %} - -``in`` operator -^^^^^^^^^^^^^^^ - -Contained within. This operator is supported by many Python containers to test -whether the given value is in the container. The following are some examples of -how ``x in y`` will be interpreted:: - - {% if "bc" in "abcdef" %} - This appears since "bc" is a substring of "abcdef" - {% endif %} - - {% if "hello" in greetings %} - If greetings is a list or set, one element of which is the string - "hello", this will appear. - {% endif %} - - {% if user in users %} - If users is a QuerySet, this will appear if user is an - instance that belongs to the QuerySet. - {% endif %} - -``not in`` operator -~~~~~~~~~~~~~~~~~~~~ - -Not contained within. This is the negation of the ``in`` operator. - - -The comparison operators cannot be 'chained' like in Python or in mathematical -notation. For example, instead of using:: - - {% if a > b > c %} (WRONG) - -you should use:: - - {% if a > b and b > c %} - - -Filters -^^^^^^^ - -You can also use filters in the ``if`` expression. For example:: - - {% if messages|length >= 100 %} - You have lots of messages today! - {% endif %} - -Complex expressions -^^^^^^^^^^^^^^^^^^^ - -All of the above can be combined to form complex expressions. For such -expressions, it can be important to know how the operators are grouped when the -expression is evaluated - that is, the precedence rules. The precedence of the -operators, from lowest to highest, is as follows: - - * ``or`` - * ``and`` - * ``not`` - * ``in`` - * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=`` - -(This follows Python exactly). So, for example, the following complex if tag: - - {% if a == b or c == d and e %} - -...will be interpreted as: - -.. code-block:: python - - (a == b) or ((c == d) and e) - -If you need different precedence, you will need to use nested if tags. Sometimes -that is better for clarity anyway, for the sake of those who do not know the -precedence rules. - - -.. templatetag:: ifchanged - -ifchanged -~~~~~~~~~ - -Check if a value has changed from the last iteration of a loop. - -The 'ifchanged' block tag is used within a loop. It has two possible uses. - -1. Checks its own rendered contents against its previous state and only - displays the content if it has changed. For example, this displays a list of - days, only displaying the month if it changes:: - - <h1>Archive for {{ year }}</h1> - - {% for date in days %} - {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} - <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> - {% endfor %} - -2. If given a variable, check whether that variable has changed. For - example, the following shows the date every time it changes, but - only shows the hour if both the hour and the date has changed:: - - {% for date in days %} - {% ifchanged date.date %} {{ date.date }} {% endifchanged %} - {% ifchanged date.hour date.date %} - {{ date.hour }} - {% endifchanged %} - {% endfor %} - -The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that -will be displayed if the value has not changed:: - - {% for match in matches %} - <div style="background-color: - {% ifchanged match.ballot_id %} - {% cycle "red" "blue" %} - {% else %} - grey - {% endifchanged %} - ">{{ match }}</div> - {% endfor %} - -.. templatetag:: ifequal - -ifequal -~~~~~~~ - -Output the contents of the block if the two arguments equal each other. - -Example:: - - {% ifequal user.id comment.user_id %} - ... - {% endifequal %} - -As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional. - -The arguments can be hard-coded strings, so the following is valid:: - - {% ifequal user.username "adrian" %} - ... - {% endifequal %} - -It is only possible to compare an argument to template variables or strings. -You cannot check for equality with Python objects such as ``True`` or -``False``. If you need to test if something is true or false, use the ``if`` -tag instead. - -.. versionadded:: 1.2 - An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator. - -.. templatetag:: ifnotequal - -ifnotequal -~~~~~~~~~~ - -Just like ``ifequal``, except it tests that the two arguments are not equal. - -.. versionadded:: 1.2 - An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator. - -.. templatetag:: include - -include -~~~~~~~ - -Loads a template and renders it with the current context. This is a way of -"including" other templates within a template. - -The template name can either be a variable or a hard-coded (quoted) string, -in either single or double quotes. - -This example includes the contents of the template ``"foo/bar.html"``:: - - {% include "foo/bar.html" %} - -This example includes the contents of the template whose name is contained in -the variable ``template_name``:: - - {% include template_name %} - -An included template is rendered with the context of the template that's -including it. This example produces the output ``"Hello, John"``: - - * Context: variable ``person`` is set to ``"john"``. - * Template:: - - {% include "name_snippet.html" %} - - * The ``name_snippet.html`` template:: - - Hello, {{ person }} - -See also: ``{% ssi %}``. - -.. note:: - The :ttag:`include` tag should be considered as an implementation of - "render this subtemplate and include the HTML", not as "parse this - subtemplate and include its contents as if it were part of the parent". - This means that there is no shared state between included templates -- - each include is a completely independent rendering process. - -.. templatetag:: load - -load -~~~~ - -Load a custom template tag set. - -See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for more information. - -.. templatetag:: now - -now -~~~ - -Display the current date and/or time, according to the given string. - -Given format can be one of the predefined ones ``DATE_FORMAT``, -``DATETIME_FORMAT``, ``SHORT_DATE_FORMAT`` or ``SHORT_DATETIME_FORMAT``, -or a custom format, same as the :tfilter:`date` filter. Note that predefined -formats may vary depending on the current locale. - -Example:: - - It is {% now "jS F Y H:i" %} - -Note that you can backslash-escape a format string if you want to use the -"raw" value. In this example, "f" is backslash-escaped, because otherwise -"f" is a format string that displays the time. The "o" doesn't need to be -escaped, because it's not a format character:: - - It is the {% now "jS o\f F" %} - -This would display as "It is the 4th of September". - -.. templatetag:: regroup - -regroup -~~~~~~~ - -Regroup a list of alike objects by a common attribute. - -This complex tag is best illustrated by use of an example: say that ``people`` -is a list of people represented by dictionaries with ``first_name``, -``last_name``, and ``gender`` keys: - -.. code-block:: python - - people = [ - {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'}, - {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'}, - {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'}, - {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'}, - {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'}, - ] - -...and you'd like to display a hierarchical list that is ordered by gender, -like this: - - * Male: - * George Bush - * Bill Clinton - * Female: - * Margaret Thatcher - * Condoleezza Rice - * Unknown: - * Pat Smith - -You can use the ``{% regroup %}`` tag to group the list of people by gender. -The following snippet of template code would accomplish this:: - - {% regroup people by gender as gender_list %} - - <ul> - {% for gender in gender_list %} - <li>{{ gender.grouper }} - <ul> - {% for item in gender.list %} - <li>{{ item.first_name }} {{ item.last_name }}</li> - {% endfor %} - </ul> - </li> - {% endfor %} - </ul> - -Let's walk through this example. ``{% regroup %}`` takes three arguments: the -list you want to regroup, the attribute to group by, and the name of the -resulting list. Here, we're regrouping the ``people`` list by the ``gender`` -attribute and calling the result ``gender_list``. - -``{% regroup %}`` produces a list (in this case, ``gender_list``) of -**group objects**. Each group object has two attributes: - - * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or - "Female"). - * ``list`` -- a list of all items in this group (e.g., a list of all people - with gender='Male'). - -Note that ``{% regroup %}`` does not order its input! Our example relies on -the fact that the ``people`` list was ordered by ``gender`` in the first place. -If the ``people`` list did *not* order its members by ``gender``, the regrouping -would naively display more than one group for a single gender. For example, -say the ``people`` list was set to this (note that the males are not grouped -together): - -.. code-block:: python - - people = [ - {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'}, - {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'}, - {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'}, - {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'}, - {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'}, - ] - -With this input for ``people``, the example ``{% regroup %}`` template code -above would result in the following output: - - * Male: - * Bill Clinton - * Unknown: - * Pat Smith - * Female: - * Margaret Thatcher - * Male: - * George Bush - * Female: - * Condoleezza Rice - -The easiest solution to this gotcha is to make sure in your view code that the -data is ordered according to how you want to display it. - -Another solution is to sort the data in the template using the ``dictsort`` -filter, if your data is in a list of dictionaries:: - - {% regroup people|dictsort:"gender" by gender as gender_list %} - -.. templatetag:: spaceless - -spaceless -~~~~~~~~~ - -Removes whitespace between HTML tags. This includes tab -characters and newlines. - -Example usage:: - - {% spaceless %} - <p> - <a href="foo/">Foo</a> - </p> - {% endspaceless %} - -This example would return this HTML:: - - <p><a href="foo/">Foo</a></p> - -Only space between *tags* is removed -- not space between tags and text. In -this example, the space around ``Hello`` won't be stripped:: - - {% spaceless %} - <strong> - Hello - </strong> - {% endspaceless %} - -.. templatetag:: ssi - -ssi -~~~ - -Output the contents of a given file into the page. - -Like a simple "include" tag, ``{% ssi %}`` includes the contents of another -file -- which must be specified using an absolute path -- in the current -page:: - - {% ssi /home/html/ljworld.com/includes/right_generic.html %} - -If the optional "parsed" parameter is given, the contents of the included -file are evaluated as template code, within the current context:: - - {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} - -Note that if you use ``{% ssi %}``, you'll need to define -:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure. - -See also: ``{% include %}``. - -.. templatetag:: templatetag - -templatetag -~~~~~~~~~~~ - -Output one of the syntax characters used to compose template tags. - -Since the template system has no concept of "escaping", to display one of the -bits used in template tags, you must use the ``{% templatetag %}`` tag. - -The argument tells which template bit to output: - - ================== ======= - Argument Outputs - ================== ======= - ``openblock`` ``{%`` - ``closeblock`` ``%}`` - ``openvariable`` ``{{`` - ``closevariable`` ``}}`` - ``openbrace`` ``{`` - ``closebrace`` ``}`` - ``opencomment`` ``{#`` - ``closecomment`` ``#}`` - ================== ======= - -.. templatetag:: url - -url -~~~ - -Returns an absolute path reference (a URL without the domain name) matching a -given view function and optional parameters. This is a way to output links -without violating the DRY principle by having to hard-code URLs in your -templates:: - - {% url path.to.some_view v1 v2 %} - -The first argument is a path to a view function in the format -``package.package.module.function``. Additional arguments are optional and -should be space-separated values that will be used as arguments in the URL. -The example above shows passing positional arguments. Alternatively you may -use keyword syntax:: - - {% url path.to.some_view arg1=v1 arg2=v2 %} - -Do not mix both positional and keyword syntax in a single call. All arguments -required by the URLconf should be present. - -For example, suppose you have a view, ``app_views.client``, whose URLconf -takes a client ID (here, ``client()`` is a method inside the views file -``app_views.py``). The URLconf line might look like this: - -.. code-block:: python - - ('^client/(\d+)/$', 'app_views.client') - -If this app's URLconf is included into the project's URLconf under a path -such as this: - -.. code-block:: python - - ('^clients/', include('project_name.app_name.urls')) - -...then, in a template, you can create a link to this view like this:: - - {% url app_views.client client.id %} - -The template tag will output the string ``/clients/client/123/``. - -.. versionadded:: 1.0 - -If you're using :ref:`named URL patterns <naming-url-patterns>`, you can -refer to the name of the pattern in the ``url`` tag instead of using the -path to the view. - -Note that if the URL you're reversing doesn't exist, you'll get an -:exc:`NoReverseMatch` exception raised, which will cause your site to display an -error page. - -.. versionadded:: 1.0 - -If you'd like to retrieve a URL without displaying it, you can use a slightly -different call:: - - - {% url path.to.view arg arg2 as the_url %} - - <a href="{{ the_url }}">I'm linking to {{ the_url }}</a> - -This ``{% url ... as var %}`` syntax will *not* cause an error if the view is -missing. In practice you'll use this to link to views that are optional:: - - {% url path.to.view as the_url %} - {% if the_url %} - <a href="{{ the_url }}">Link to optional stuff</a> - {% endif %} - -.. versionadded:: 1.1 - -If you'd like to retrieve a namespaced URL, specify the fully qualified name:: - - {% url myapp:view-name %} - -This will follow the normal :ref:`namespaced URL resolution strategy -<topics-http-reversing-url-namespaces>`, including using any hints provided -by the context as to the current application. - -.. versionchanged:: 1.2 - -For backwards compatibility, the ``{% url %}`` tag also supports the -use of commas to separate arguments. You shouldn't use this in any new -projects, but for the sake of the people who are still using it, -here's what it looks like:: - - {% url path.to.view arg,arg2 %} - {% url path.to.view arg, arg2 %} - -This syntax doesn't support the use of literal commas, or or equals -signs. Did we mention you shouldn't use this syntax in any new -projects? - -.. templatetag:: widthratio - -widthratio -~~~~~~~~~~ - -For creating bar charts and such, this tag calculates the ratio of a given value -to a maximum value, and then applies that ratio to a constant. - -For example:: - - <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" /> - -Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the -above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 -which is rounded up to 88). - -.. templatetag:: with - -with -~~~~ - -.. versionadded:: 1.0 - -Caches a complex variable under a simpler name. This is useful when accessing -an "expensive" method (e.g., one that hits the database) multiple times. - -For example:: - - {% with business.employees.count as total %} - {{ total }} employee{{ total|pluralize }} - {% endwith %} - -The populated variable (in the example above, ``total``) is only available -between the ``{% with %}`` and ``{% endwith %}`` tags. - -.. _ref-templates-builtins-filters: - -Built-in filter reference -------------------------- - -.. templatefilter:: add - -add -~~~ - -Adds the argument to the value. - -For example:: - - {{ value|add:"2" }} - -If ``value`` is ``4``, then the output will be ``6``. - -.. versionchanged:: 1.2 - The following behavior didn't exist in previous Django versions. - -This filter will first try to coerce both values to integers. If this fails, -it'll attempt to add the values together anyway. This will work on some data -types (strings, list, etc.) and fail on others. If it fails, the result will -be an empty string. - -For example, if we have:: - - {{ first|add:second }} - -and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the -output will be ``[1, 2, 3, 4, 5, 6]``. - -.. warning:: - - Strings that can be coerced to integers will be **summed**, not - concatenated, as in the first example above. - -.. templatefilter:: addslashes - -addslashes -~~~~~~~~~~ - -Adds slashes before quotes. Useful for escaping strings in CSV, for example. - -For example:: - - {{ value|addslashes }} - -If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``. - -.. templatefilter:: capfirst - -capfirst -~~~~~~~~ - -Capitalizes the first character of the value. - -For example:: - - {{ value|capfirst }} - -If ``value`` is ``"django"``, the output will be ``"Django"``. - -.. templatefilter:: center - -center -~~~~~~ - -Centers the value in a field of a given width. - -For example:: - - "{{ value|center:"15" }}" - -If ``value`` is ``"Django"``, the output will be ``" Django "``. - -.. templatefilter:: cut - -cut -~~~ - -Removes all values of arg from the given string. - -For example:: - - {{ value|cut:" "}} - -If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``. - -.. templatefilter:: date - -date -~~~~ - -Formats a date according to the given format. - -Uses the same format as PHP's ``date()`` function (http://php.net/date) -with some custom extensions. - -Available format strings: - - ================ ======================================== ===================== - Format character Description Example output - ================ ======================================== ===================== - a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'`` - this is slightly different than PHP's - output, because this includes periods - to match Associated Press style.) - A ``'AM'`` or ``'PM'``. ``'AM'`` - b Month, textual, 3 letters, lowercase. ``'jan'`` - B Not implemented. - c ISO 8601 Format. ``2008-01-02T10:30:00.000123`` - d Day of the month, 2 digits with ``'01'`` to ``'31'`` - leading zeros. - D Day of the week, textual, 3 letters. ``'Fri'`` - f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'`` - with minutes left off if they're zero. - Proprietary extension. - F Month, textual, long. ``'January'`` - g Hour, 12-hour format without leading ``'1'`` to ``'12'`` - zeros. - G Hour, 24-hour format without leading ``'0'`` to ``'23'`` - zeros. - h Hour, 12-hour format. ``'01'`` to ``'12'`` - H Hour, 24-hour format. ``'00'`` to ``'23'`` - i Minutes. ``'00'`` to ``'59'`` - I Not implemented. - j Day of the month without leading ``'1'`` to ``'31'`` - zeros. - l Day of the week, textual, long. ``'Friday'`` - L Boolean for whether it's a leap year. ``True`` or ``False`` - m Month, 2 digits with leading zeros. ``'01'`` to ``'12'`` - M Month, textual, 3 letters. ``'Jan'`` - n Month without leading zeros. ``'1'`` to ``'12'`` - N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'`` - style. Proprietary extension. - O Difference to Greenwich time in hours. ``'+0200'`` - P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'`` - 'a.m.'/'p.m.', with minutes left off - if they're zero and the special-case - strings 'midnight' and 'noon' if - appropriate. Proprietary extension. - r RFC 2822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'`` - s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'`` - S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'`` - month, 2 characters. - t Number of days in the given month. ``28`` to ``31`` - T Time zone of this machine. ``'EST'``, ``'MDT'`` - u Microseconds. ``0`` to ``999999`` - U Seconds since the Unix Epoch - (January 1 1970 00:00:00 UTC). - w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday) - leading zeros. - W ISO-8601 week number of year, with ``1``, ``53`` - weeks starting on Monday. - y Year, 2 digits. ``'99'`` - Y Year, 4 digits. ``'1999'`` - z Day of the year. ``0`` to ``365`` - Z Time zone offset in seconds. The ``-43200`` to ``43200`` - offset for timezones west of UTC is - always negative, and for those east of - UTC is always positive. - ================ ======================================== ===================== - -.. versionadded:: 1.2 - -The ``c`` and ``u`` format specification characters were added in Django 1.2. - -For example:: - - {{ value|date:"D d M Y" }} - -If ``value`` is a ``datetime`` object (e.g., the result of -``datetime.datetime.now()``), the output will be the string -``'Wed 09 Jan 2008'``. - -The format passed can be one of the predefined ones ``DATE_FORMAT``, -``DATETIME_FORMAT``, ``SHORT_DATE_FORMAT`` or ``SHORT_DATETIME_FORMAT``, or a -custom format that uses the format specifiers shown in the table above. Note -that predefined formats may vary depending on the current locale. - -Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is, -for example, ``"es"``, then for:: - - {{ value|date:"SHORT_DATE_FORMAT" }} - -the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"`` -format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``). - -When used without a format string:: - - {{ value|date }} - -...the formatting string defined in the :setting:`DATE_FORMAT` setting will be -used, without applying any localization. - -.. versionchanged:: 1.2 - Predefined formats can now be influenced by the current locale. - -.. templatefilter:: default - -default -~~~~~~~ - -If value evaluates to ``False``, use given default. Otherwise, use the value. - -For example:: - - {{ value|default:"nothing" }} - -If ``value`` is ``""`` (the empty string), the output will be ``nothing``. - -.. templatefilter:: default_if_none - -default_if_none -~~~~~~~~~~~~~~~ - -If (and only if) value is ``None``, use given default. Otherwise, use the -value. - -Note that if an empty string is given, the default value will *not* be used. -Use the ``default`` filter if you want to fallback for empty strings. - -For example:: - - {{ value|default_if_none:"nothing" }} - -If ``value`` is ``None``, the output will be the string ``"nothing"``. - -.. templatefilter:: dictsort - -dictsort -~~~~~~~~ - -Takes a list of dictionaries and returns that list sorted by the key given in -the argument. - -For example:: - - {{ value|dictsort:"name" }} - -If ``value`` is: - -.. code-block:: python - - [ - {'name': 'zed', 'age': 19}, - {'name': 'amy', 'age': 22}, - {'name': 'joe', 'age': 31}, - ] - -then the output would be: - -.. code-block:: python - - [ - {'name': 'amy', 'age': 22}, - {'name': 'joe', 'age': 31}, - {'name': 'zed', 'age': 19}, - ] - -.. templatefilter:: dictsortreversed - -dictsortreversed -~~~~~~~~~~~~~~~~ - -Takes a list of dictionaries and returns that list sorted in reverse order by -the key given in the argument. This works exactly the same as the above filter, -but the returned value will be in reverse order. - -.. templatefilter:: divisibleby - -divisibleby -~~~~~~~~~~~ - -Returns ``True`` if the value is divisible by the argument. - -For example:: - - {{ value|divisibleby:"3" }} - -If ``value`` is ``21``, the output would be ``True``. - -.. templatefilter:: escape - -escape -~~~~~~ - -Escapes a string's HTML. Specifically, it makes these replacements: - - * ``<`` is converted to ``<`` - * ``>`` is converted to ``>`` - * ``'`` (single quote) is converted to ``'`` - * ``"`` (double quote) is converted to ``"`` - * ``&`` is converted to ``&`` - -The escaping is only applied when the string is output, so it does not matter -where in a chained sequence of filters you put ``escape``: it will always be -applied as though it were the last filter. If you want escaping to be applied -immediately, use the ``force_escape`` filter. - -Applying ``escape`` to a variable that would normally have auto-escaping -applied to the result will only result in one round of escaping being done. So -it is safe to use this function even in auto-escaping environments. If you want -multiple escaping passes to be applied, use the ``force_escape`` filter. - -.. versionchanged:: 1.0 - Due to auto-escaping, the behavior of this filter has changed slightly. - The replacements are only made once, after - all other filters are applied -- including filters before and after it. - -.. templatefilter:: escapejs - -escapejs -~~~~~~~~ - -.. versionadded:: 1.0 - -Escapes characters for use in JavaScript strings. This does *not* make the -string safe for use in HTML, but does protect you from syntax errors when using -templates to generate JavaScript/JSON. - -For example:: - - {{ value|escapejs }} - -If ``value`` is ``"testing\r\njavascript \'string" <b>escaping</b>"``, -the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"``. - -.. templatefilter:: filesizeformat - -filesizeformat -~~~~~~~~~~~~~~ - -Format the value like a 'human-readable' file size (i.e. ``'13 KB'``, -``'4.1 MB'``, ``'102 bytes'``, etc). - -For example:: - - {{ value|filesizeformat }} - -If ``value`` is 123456789, the output would be ``117.7 MB``. - -.. templatefilter:: first - -first -~~~~~ - -Returns the first item in a list. - -For example:: - - {{ value|first }} - -If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``. - -.. templatefilter:: fix_ampersands - -fix_ampersands -~~~~~~~~~~~~~~ - -.. versionchanged:: 1.0 - This is rarely useful as ampersands are now automatically escaped. See escape_ for more information. - -Replaces ampersands with ``&`` entities. - -For example:: - - {{ value|fix_ampersands }} - -If ``value`` is ``Tom & Jerry``, the output will be ``Tom & Jerry``. - -.. templatefilter:: floatformat - -floatformat -~~~~~~~~~~~ - -When used without an argument, rounds a floating-point number to one decimal -place -- but only if there's a decimal part to be displayed. For example: - -============ =========================== ======== -``value`` Template Output -============ =========================== ======== -``34.23234`` ``{{ value|floatformat }}`` ``34.2`` -``34.00000`` ``{{ value|floatformat }}`` ``34`` -``34.26000`` ``{{ value|floatformat }}`` ``34.3`` -============ =========================== ======== - -If used with a numeric integer argument, ``floatformat`` rounds a number to -that many decimal places. For example: - -============ ============================= ========== -``value`` Template Output -============ ============================= ========== -``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232`` -``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000`` -``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260`` -============ ============================= ========== - -If the argument passed to ``floatformat`` is negative, it will round a number -to that many decimal places -- but only if there's a decimal part to be -displayed. For example: - -============ ================================ ========== -``value`` Template Output -============ ================================ ========== -``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232`` -``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34`` -``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260`` -============ ================================ ========== - -Using ``floatformat`` with no argument is equivalent to using ``floatformat`` -with an argument of ``-1``. - -.. templatefilter:: force_escape - -force_escape -~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -Applies HTML escaping to a string (see the ``escape`` filter for details). -This filter is applied *immediately* and returns a new, escaped string. This -is useful in the rare cases where you need multiple escaping or want to apply -other filters to the escaped results. Normally, you want to use the ``escape`` -filter. - -.. templatefilter:: get_digit - -get_digit -~~~~~~~~~ - -Given a whole number, returns the requested digit, where 1 is the right-most -digit, 2 is the second-right-most digit, etc. Returns the original value for -invalid input (if input or argument is not an integer, or if argument is less -than 1). Otherwise, output is always an integer. - -For example:: - - {{ value|get_digit:"2" }} - -If ``value`` is ``123456789``, the output will be ``8``. - -.. templatefilter:: iriencode - -iriencode -~~~~~~~~~ - -Converts an IRI (Internationalized Resource Identifier) to a string that is -suitable for including in a URL. This is necessary if you're trying to use -strings containing non-ASCII characters in a URL. - -It's safe to use this filter on a string that has already gone through the -``urlencode`` filter. - -For example:: - - {{ value|iriencode }} - -If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&me=2"``. - -.. templatefilter:: join - -join -~~~~ - -Joins a list with a string, like Python's ``str.join(list)`` - -For example:: - - {{ value|join:" // " }} - -If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string -``"a // b // c"``. - -.. templatefilter:: last - -last -~~~~ - -.. versionadded:: 1.0 - -Returns the last item in a list. - -For example:: - - {{ value|last }} - -If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string -``"d"``. - -.. templatefilter:: length - -length -~~~~~~ - -Returns the length of the value. This works for both strings and lists. - -For example:: - - {{ value|length }} - -If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``. - -.. templatefilter:: length_is - -length_is -~~~~~~~~~ - -Returns ``True`` if the value's length is the argument, or ``False`` otherwise. - -For example:: - - {{ value|length_is:"4" }} - -If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``. - -.. templatefilter:: linebreaks - -linebreaks -~~~~~~~~~~ - -Replaces line breaks in plain text with appropriate HTML; a single -newline becomes an HTML line break (``<br />``) and a new line -followed by a blank line becomes a paragraph break (``</p>``). - -For example:: - - {{ value|linebreaks }} - -If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br />is a -slug</p>``. - -.. templatefilter:: linebreaksbr - -linebreaksbr -~~~~~~~~~~~~ - -Converts all newlines in a piece of plain text to HTML line breaks -(``<br />``). - -For example:: - - {{ value|linebreaksbr }} - -If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br />is a -slug``. - -.. templatefilter:: linenumbers - -linenumbers -~~~~~~~~~~~ - -Displays text with line numbers. - -For example:: - - {{ value|linenumbers }} - -If ``value`` is:: - - one - two - three - -the output will be:: - - 1. one - 2. two - 3. three - -.. templatefilter:: ljust - -ljust -~~~~~ - -Left-aligns the value in a field of a given width. - -**Argument:** field size - -For example:: - - "{{ value|ljust:"10" }}" - -If ``value`` is ``Django``, the output will be ``"Django "``. - -.. templatefilter:: lower - -lower -~~~~~ - -Converts a string into all lowercase. - -For example:: - - {{ value|lower }} - -If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``. - -.. templatefilter:: make_list - -make_list -~~~~~~~~~ - -Returns the value turned into a list. For an integer, it's a list of -digits. For a string, it's a list of characters. - -For example:: - - {{ value|make_list }} - -If ``value`` is the string ``"Joel"``, the output would be the list -``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the -list ``[1, 2, 3]``. - -.. templatefilter:: phone2numeric - -phone2numeric -~~~~~~~~~~~~~ - -Converts a phone number (possibly containing letters) to its numerical -equivalent. - -The input doesn't have to be a valid phone number. This will happily convert -any string. - -For example:: - - {{ value|phone2numeric }} - -If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``. - -.. templatefilter:: pluralize - -pluralize -~~~~~~~~~ - -Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``. - -Example:: - - You have {{ num_messages }} message{{ num_messages|pluralize }}. - -If ``num_messages`` is ``1``, the output will be ``You have 1 message.`` -If ``num_messages`` is ``2`` the output will be ``You have 2 messages.`` - -For words that require a suffix other than ``'s'``, you can provide an alternate -suffix as a parameter to the filter. - -Example:: - - You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}. - -For words that don't pluralize by simple suffix, you can specify both a -singular and plural suffix, separated by a comma. - -Example:: - - You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}. - -.. templatefilter:: pprint - -pprint -~~~~~~ - -A wrapper around `pprint.pprint`__ -- for debugging, really. - -__ http://docs.python.org/library/pprint.html - -.. templatefilter:: random - -random -~~~~~~ - -Returns a random item from the given list. - -For example:: - - {{ value|random }} - -If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``. - -.. templatefilter:: removetags - -removetags -~~~~~~~~~~ - -Removes a space-separated list of [X]HTML tags from the output. - -For example:: - - {{ value|removetags:"b span"|safe }} - -If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the -output will be ``"Joel <button>is</button> a slug"``. - -Note that this filter is case-sensitive. - -If ``value`` is ``"<B>Joel</B> <button>is</button> a <span>slug</span>"`` the -output will be ``"<B>Joel</B> <button>is</button> a slug"``. - -.. templatefilter:: rjust - -rjust -~~~~~ - -Right-aligns the value in a field of a given width. - -**Argument:** field size - -For example:: - - "{{ value|rjust:"10" }}" - -If ``value`` is ``Django``, the output will be ``" Django"``. - -.. templatefilter:: safe - -safe -~~~~ - -Marks a string as not requiring further HTML escaping prior to output. When -autoescaping is off, this filter has no effect. - -.. note:: - - If you are chaining filters, a filter applied after ``safe`` can - make the contents unsafe again. For example, the following code - prints the variable as is, unescaped: - - .. code-block:: html+django - - {{ var|safe|escape }} - -.. templatefilter:: safeseq - -safeseq -~~~~~~~ - -Applies the :tfilter:`safe` filter to each element of a sequence. Useful in -conjunction with other filters that operate on sequences, such as -:tfilter:`join`. For example:: - - {{ some_list|safeseq|join:", " }} - -You couldn't use the :tfilter:`safe` filter directly in this case, as it would -first convert the variable into a string, rather than working with the -individual elements of the sequence. - -.. templatefilter:: slice - -slice -~~~~~ - -Returns a slice of the list. - -Uses the same syntax as Python's list slicing. See -http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice -for an introduction. - -Example:: - - {{ some_list|slice:":2" }} - -If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``. - -.. templatefilter:: slugify - -slugify -~~~~~~~ - -Converts to lowercase, removes non-word characters (alphanumerics and -underscores) and converts spaces to hyphens. Also strips leading and trailing -whitespace. - -For example:: - - {{ value|slugify }} - -If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``. - -.. templatefilter:: stringformat - -stringformat -~~~~~~~~~~~~ - -Formats the variable according to the argument, a string formatting specifier. -This specifier uses Python string formatting syntax, with the exception that -the leading "%" is dropped. - -See http://docs.python.org/library/stdtypes.html#string-formatting-operations -for documentation of Python string formatting - -For example:: - - {{ value|stringformat:"s" }} - -If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``. - -.. templatefilter:: striptags - -striptags -~~~~~~~~~ - -Strips all [X]HTML tags. - -For example:: - - {{ value|striptags }} - -If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the -output will be ``"Joel is a slug"``. - -.. templatefilter:: time - -time -~~~~ - -Formats a time according to the given format. - -Given format can be the predefined one ``TIME_FORMAT``, or a custom format, -same as the :tfilter:`date` filter. Note that the predefined format is locale- -dependant. - -The time filter will only accept parameters in the format string that relate -to the time of day, not the date (for obvious reasons). If you need to -format a date, use the :tfilter:`date` filter. - -For example:: - - {{ value|time:"H:i" }} - -If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be -the string ``"01:23"``. - -Another example: - -Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is, -for example, ``"de"``, then for:: - - {{ value|time:"TIME_FORMAT" }} - -the output will be the string ``"01:23:00"`` (The ``"TIME_FORMAT"`` format -specifier for the ``de`` locale as shipped with Django is ``"H:i:s"``). - -When used without a format string:: - - {{ value|time }} - -...the formatting string defined in the :setting:`TIME_FORMAT` setting will be -used, without applying any localization. - -.. versionchanged:: 1.2 - Predefined formats can now be influenced by the current locale. - -.. templatefilter:: timesince - -timesince -~~~~~~~~~ - -Formats a date as the time since that date (e.g., "4 days, 6 hours"). - -Takes an optional argument that is a variable containing the date to use as -the comparison point (without the argument, the comparison point is *now*). -For example, if ``blog_date`` is a date instance representing midnight on 1 -June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006, -then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours". - -Comparing offset-naive and offset-aware datetimes will return an empty string. - -Minutes is the smallest unit used, and "0 minutes" will be returned for any -date that is in the future relative to the comparison point. - -.. templatefilter:: timeuntil - -timeuntil -~~~~~~~~~ - -Similar to ``timesince``, except that it measures the time from now until the -given date or datetime. For example, if today is 1 June 2006 and -``conference_date`` is a date instance holding 29 June 2006, then -``{{ conference_date|timeuntil }}`` will return "4 weeks". - -Takes an optional argument that is a variable containing the date to use as -the comparison point (instead of *now*). If ``from_date`` contains 22 June -2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week". - -Comparing offset-naive and offset-aware datetimes will return an empty string. - -Minutes is the smallest unit used, and "0 minutes" will be returned for any -date that is in the past relative to the comparison point. - -.. templatefilter:: title - -title -~~~~~ - -Converts a string into titlecase. - -For example:: - - {{ value|title }} - -If ``value`` is ``"my first post"``, the output will be ``"My First Post"``. - -.. templatefilter:: truncatewords - -truncatewords -~~~~~~~~~~~~~ - -Truncates a string after a certain number of words. - -**Argument:** Number of words to truncate after - -For example:: - - {{ value|truncatewords:2 }} - -If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``. - -Newlines within the string will be removed. - -.. templatefilter:: truncatewords_html - -truncatewords_html -~~~~~~~~~~~~~~~~~~ - -Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags -that are opened in the string and not closed before the truncation point, are -closed immediately after the truncation. - -This is less efficient than ``truncatewords``, so should only be used when it -is being passed HTML text. - -For example:: - - {{ value|truncatewords_html:2 }} - -If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be -``"<p>Joel is ...</p>"``. - -Newlines in the HTML content will be preserved. - -.. templatefilter:: unordered_list - -unordered_list -~~~~~~~~~~~~~~ - -Recursively takes a self-nested list and returns an HTML unordered list -- -WITHOUT opening and closing <ul> tags. - -.. versionchanged:: 1.0 - The format accepted by ``unordered_list`` has changed to be easier to understand. - -The list is assumed to be in the proper format. For example, if ``var`` contains -``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then -``{{ var|unordered_list }}`` would return:: - - <li>States - <ul> - <li>Kansas - <ul> - <li>Lawrence</li> - <li>Topeka</li> - </ul> - </li> - <li>Illinois</li> - </ul> - </li> - -Note: the previous more restrictive and verbose format is still supported: -``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``, - -.. templatefilter:: upper - -upper -~~~~~ - -Converts a string into all uppercase. - -For example:: - - {{ value|upper }} - -If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``. - -.. templatefilter:: urlencode - -urlencode -~~~~~~~~~ - -Escapes a value for use in a URL. - -For example:: - - {{ value|urlencode }} - -If ``value`` is ``"http://www.example.org/foo?a=b&c=d"``, the output will be -``"http%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``. - -.. templatefilter:: urlize - -urlize -~~~~~~ - -Converts URLs in plain text into clickable links. - -Note that if ``urlize`` is applied to text that already contains HTML markup, -things won't work as expected. Apply this filter only to *plain* text. - -For example:: - - {{ value|urlize }} - -If ``value`` is ``"Check out www.djangoproject.com"``, the output will be -``"Check out <a -href="http://www.djangoproject.com">www.djangoproject.com</a>"``. - -.. templatefilter:: urlizetrunc - -urlizetrunc -~~~~~~~~~~~ - -Converts URLs into clickable links, truncating URLs longer than the given -character limit. - -As with urlize_, this filter should only be applied to *plain* text. - -**Argument:** Length to truncate URLs to - -For example:: - - {{ value|urlizetrunc:15 }} - -If ``value`` is ``"Check out www.djangoproject.com"``, the output would be -``'Check out <a -href="http://www.djangoproject.com">www.djangopr...</a>'``. - -.. templatefilter:: wordcount - -wordcount -~~~~~~~~~ - -Returns the number of words. - -For example:: - - {{ value|wordcount }} - -If ``value`` is ``"Joel is a slug"``, the output will be ``4``. - -.. templatefilter:: wordwrap - -wordwrap -~~~~~~~~ - -Wraps words at specified line length. - -**Argument:** number of characters at which to wrap the text - -For example:: - - {{ value|wordwrap:5 }} - -If ``value`` is ``Joel is a slug``, the output would be:: - - Joel - is a - slug - -.. templatefilter:: yesno - -yesno -~~~~~ - -Given a string mapping values for true, false and (optionally) None, -returns one of those strings according to the value: - -For example:: - - {{ value|yesno:"yeah,no,maybe" }} - -========== ====================== ================================== -Value Argument Outputs -========== ====================== ================================== -``True`` ``"yeah,no,maybe"`` ``yeah`` -``False`` ``"yeah,no,maybe"`` ``no`` -``None`` ``"yeah,no,maybe"`` ``maybe`` -``None`` ``"yeah,no"`` ``"no"`` (converts None to False - if no mapping for None is given) -========== ====================== ================================== - -Other tags and filter libraries -------------------------------- - -Django comes with a couple of other template-tag libraries that you have to -enable explicitly in your ``INSTALLED_APPS`` setting and enable in your -template with the ``{% load %}`` tag. - -django.contrib.humanize -~~~~~~~~~~~~~~~~~~~~~~~ - -A set of Django template filters useful for adding a "human touch" to data. See -:doc:`/ref/contrib/humanize`. - -django.contrib.markup -~~~~~~~~~~~~~~~~~~~~~ - -A collection of template filters that implement these common markup languages: - - * Textile - * Markdown - * reST (reStructuredText) - -See the :doc:`markup documentation </ref/contrib/markup>`. - -django.contrib.webdesign -~~~~~~~~~~~~~~~~~~~~~~~~ - -A collection of template tags that can be useful while designing a Web site, -such as a generator of Lorem Ipsum text. See :doc:`/ref/contrib/webdesign`. - -i18n -~~~~ - -Provides a couple of templatetags that allow specifying translatable text in -Django templates. It is slightly different from the libraries described -above because you don't need to add any application to the ``INSTALLED_APPS`` -setting but rather set :setting:`USE_I18N` to True, then loading it with -``{% load i18n %}``. See :ref:`specifying-translation-strings-in-template-code`. diff --git a/parts/django/docs/ref/templates/index.txt b/parts/django/docs/ref/templates/index.txt deleted file mode 100644 index 0aa4798..0000000 --- a/parts/django/docs/ref/templates/index.txt +++ /dev/null @@ -1,19 +0,0 @@ -========= -Templates -========= - -Django's template engine provides a powerful mini-language for defining the -user-facing layer of your application, encouraging a clean separation of -application and presentation logic. Templates can be maintained by anyone with -an understanding of HTML; no knowledge of Python is required. - -.. toctree:: - :maxdepth: 2 - - builtins - api - -.. seealso:: - - For information on writing your own custom tags and filters, see - :doc:`/howto/custom-template-tags`. |