============================ The Django template language ============================ Django's template language is designed to strike a balance between power and ease; it's designed to feel comfortable to those used to working with HTML. If you have any exposure to other text-based template languages like Smarty_ or CheetahTemplate_, you should feel right at home with Django's templates. .. _Smarty: http://smarty.php.net/ .. _CheetahTemplate: http://www.cheetahtemplate.org/ What's a template? ================== A template is simply a text file. All Django templates by convention have ".html" extensions, but they can actually generate any text-based format (HTML, XML, CSV, etc.). To actually be useful, a template will contain **variables**, which get replaced with values from the database when the template is evaluated, and **tags**, which control the logic of the template. Below is a minimal template that illustrates the basic parts of a template. Each element will be explained later in this document.:: {% extends "base_generic" %} {% block title %}{{ section.title }}{% endblock %} {% block content %}

{{ section.title }}

{% for story in story_list %}

{{ story.headline|upper }}

{{ story.tease|truncatewords:"100" }}

{% endfor %} {% endblock %} What's a variable? ================== Variables look like this: ``{{ variable }}``. When the template engine encounters a variable, it evaluates that variable and replaces the variable with the result. Many variables will be structures with named attributes; you can "drill down" into these structures with dots (``.``), so in the above example ``{{ section.title }}`` will be replaced with the ``title`` attribute of the ``section`` object. If you use a variable that doesn't exist, it will be silently ignored; the variable will be replaced by nothingness. See `Using the built-in reference`_, below, for help on finding what variables are available in a given template. Variables may be modified before being displayed by **filters**. What's a filter? ================ Filters look like this: ``{{ name|lower }}``. This displays the value of the ``{{ name }}`` variable after being filtered through the ``lower`` filter which, as you might have guessed, lowercases the text passed through it. We use the pipe character to apply filters to emphasize the analogy with filters on a water pipe: text enters one side, has some operation performed on it, and "flows" out the other side. Filters may be "chained"; the output of one filter applied to the next: ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents and then converting line breaks to ``

`` tags. Certain filters take arguments; a filter argument looks like this: ``{{ bio|truncatewords:"30" }}``. This will display the first 30 words of the ``bio`` variable. Filter arguments always are in double quotes. The `Built-in filter reference`_ below describes all the built-in filters. What's a tag? ============= Tags look like this: ``{% tag %}``. Tags are much more complex than variables: some create text in the output; some control flow by performing loops, or logic; some load external information into the template to be used by later variables. Some tags are "block" tags with matching beginning and ending tags (i.e. ``{% tag %} ... tag contents ... {% endtag %}``. The `Built-in tag reference`_ below describes all the built-in tags. Template Inheritance ==================== The most powerful -- and thus the most complex -- part of Django's template engine is template inheritance. In a nutshell, template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines **blocks** that child templates can override. It's easiest to understand template inheritance by starting with an example:: {% block title %}My Amazing Site{% endblock %}

{% block content %}{% endblock %}
This template, which we'll call ``base.html`` defines a simple HTML skeleton document that you might use for a simple two-column page. This template won't actually be used directly on any pages, but other "child" templates will extend it and fill in the empty blocks with content. I've used the ``{% block %}`` tag to define the three blocks that child templates will fill in. All that the ``block`` tag does is to signal to the template engine that a child template may override those portions of the template. To use this template, I might define a child template as follows:: {% extends "base" %} {% block title %}My Amazing Blog{% endblock %} {% block content %} {% for entry in blog_entries %}

{{ entry.title }}

{{ entry.body }}

{% endfor %} {% endblock %} The ``{% extends %}`` tag is the key here; it tells the template engine that this template "extends" another template. When this template is evaluated, the first step the template engine will perform is to locate the parent template -- in this case, "base" (note the dropping of the ".html" extension). At that point, the template engine will notice the three blocks in ``base.html``, and replace those blocks with the contents of the child template. Depending on the value of ``blog_entries``, the output might look like:: My Amazing Blog

Entry one

This is my first entry.

Entry two

This is my second entry.

Note that since the child template did not define the ``sidebar`` block, the value from the parent template is used instead. Template inheritance does not have to be only single-level; multi-level inheritance is possible, and indeed, quite useful. Here are some tips for working with inheritance: * More ``{% block %}`` tags in your base templates are better. Remember, child templates do not have to define all parent blocks, so you can fill in reasonable defaults in a number of blocks, then only define the ones you need later on. * If you find yourself reproducing the same content in a number of documents, it probably means you should move that content to a new ``{% block %}`` in a parent template. * We often prefer to use three-level inheritance: a single base template for the entire site, a set of mid-level templates for each section of the site, and then the individual templates for each page. This maximizes code reuse, and makes it easier to add items to shared content areas (like section-wide navigation). * If you need to get the content of the block from the parent template, the ``{{ block.super }}`` variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Using the built-in reference ============================ Since Django can be used to develop any sort of site, the tags, filters, and variables available will be different depending on the application. To make it simple to figure out what's available in a given site, the admin interface has a complete reference of all the template goodies available to that site. This documentation is integrated into the administration interface for your sites and is divided into 4 sections: tags, filters, models, and views. The **tags** and **filters** sections describe all the built-in tags (in fact, the tag and filter references below come directly from those pages) as well as any custom tag or filter libraries available. The **views** page is perhaps the most valuable. Each URL in your site has a separate entry here, and clicking on a URL will show you: * The name of the view function that generates that view. * A short description of what the view does. * The **context**, or a list of variables available in the view. * The name of the template or templates that are used for that view. Each view documentation page also has a bookmarklet that you can use to jump from any page to the documentation page for that view. Since most of Django revolves around database objects, the **models** section of the documentation page describes each type of object in the system along with all the fields available on that object. Taken together, the documentation pages should tell you every tag, filter, variable and object available to you in a given template. Custom tag and filter libraries =============================== As mentioned above, certain applications will provide custom tag and filter libraries. To access them in a template, use the ``{% load %}`` tag:: {% load comments %} {% comment_form for blogs.entries entry.id with is_public yes %} In the above, the ``load`` tag loads the ``comments`` tag library, which then makes the ``comment_form`` tag available for use. Consult the documentation area in your admin to find the list of custom libraries in your installation. Built-in tag and filter reference ================================= For those without an admin site available, the reference for the stock tags and filters follows. Since Django is highly customizable, the documentation references in your admin should be considered the final word on what tags and filters are available and their functions. Built-in tag reference ---------------------- ``block`` Define a block that can be overridden by child templates. See `Template inheritance`_ for more information. ``comment`` Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` ``cycle`` Cycle among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} ... {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:: ... ... ... You can use any number of values, separated by commas. Make sure not to put spaces between the values -- only commas. ``debug`` Output a whole load of debugging information, including the current context and imported modules. ``extends`` Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as the name of the parent template to extend. See `Template inheritance`_ for more information. ``filter`` Filter the contents of the blog through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter escape|lower %} This text will be HTML-escaped, and will appear in all lowercase. {% endfilter %} ``firstof`` Outputs the first variable passed that is not False. Outputs nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 %} This is equivalent to:: {% if var1 %} {{ var1 }} {% else %}{% if var2 %} {{ var2 }} {% else %}{% if var3 %} {{ var3 }} {% endif %}{% endif %}{% endif %} but obviously much cleaner! ``for`` Loop over each item in an array. For example, to display a list of athletes given ``athlete_list``:: You can also loop over a list in reverse by using ``{% for obj in list reversed %}``. 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.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 ========================== ================================================ ``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|count }} {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. As you can see, the ``if`` tag can take an option ``{% else %}`` clause that will be displayed if the test fails. ``if`` tags may use ``or`` or ``not`` to test a number of variables or to negate a given variable:: {% 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 my fault). {% endif %} For simplicity, ``if`` tags do not allow ``and`` clauses; use nested ``if`` tags instead:: {% if athlete_list %} {% if coach_list %} Number of athletes: {{ athlete_list|count }}. Number of coaches: {{ coach_list|count }}. {% endif %} {% endif %} ``ifchanged`` Check if a value has changed from the last iteration of a loop. The 'ifchanged' block tag is used within a loop. It checks its own rendered contents against its previous state and only displays its content if the value has changed::

Archive for {{ year }}

{% for date in days %} {% ifchanged %}

{{ date|date:"F" }}

{% endifchanged %} {{ date|date:"j" }} {% endfor %} ``ifnotequal`` Output the contents of the block if the two arguments do not equal each other. Example:: {% ifnotequal user.id_ comment.user_id %} ... {% endifnotequal %} ``load`` Load a custom template tag set. See `Custom tag and filter libraries`_ for more information. ``now`` Display the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values. Sample usage:: It is {% now "jS F Y H:i" %} ``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 ``Person`` objects that have ``first_name``, ``last_name``, and ``gender`` attributes, and you'd like to display a list that looks like: * Male: * George Bush * Bill Clinton * Female: * Margaret Thatcher * Colendeeza Rice * Unknown: * Janet Reno The following snippet of template code would accomplish this dubious task:: {% regroup people by gender as grouped %} As you can see, ``{% regroup %}`` populates a variable with a list of objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the item that was grouped by; ``list`` contains the list of objects that share that ``grouper``. In this case, ``grouper`` would be ``Male``, ``Female`` and ``Unknown``, and ``list`` is the list of people with those genders. Note that ``{% regroup %}`` does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of people was not sorted by gender, you'd need to make sure it is sorted before using it, i.e.:: {% regroup people|dictsort:"gender" by gender as grouped %} ``ssi`` Output the contents of a given file into the page. Like a simple "include" tag, the ``ssi`` tag includes the contents of another file -- which must be specified using an absolute page -- 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, with the current context:: {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} ``templatetag`` Output one of the bits 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`` ``}}`` ================== ======= ``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:: Above, if ``this_value`` is 175 and ``max_value`` is 200, the 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). Built-in filter reference ------------------------- ``add`` Adds the arg to the value ``addslashes`` Adds slashes - useful for passing strings to JavaScript, for example. ``capfirst`` Capitalizes the first character of the value ``center`` Centers the value in a field of a given width ``cut`` Removes all values of arg from the given string ``date`` Formats a date according to the given format (same as the ``now`` tag) ``default`` If value is unavailable, use given default ``dictsort`` Takes a list of dicts, returns that list sorted by the property given in the argument. ``dictsortreversed`` Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. ``divisibleby`` Returns true if the value is divisible by the argument ``escape`` Escapes a string's HTML ``filesizeformat`` Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). ``first`` Returns the first item in a list ``fix_ampersands`` Replaces ampersands with ``&`` entities ``floatformat`` Displays a floating point number as 34.2 (with one decimal places) - but only if there's a point to be displayed ``get_digit`` Given a whole number, returns the requested digit of it, 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. ``join`` Joins a list with a string, like Python's ``str.join(list)`` ``length`` Returns the length of the value - useful for lists ``length_is`` Returns a boolean of whether the value's length is the argument ``linebreaks`` Converts newlines into

and
s ``linebreaksbr`` Converts newlines into
s ``linenumbers`` Displays text with line numbers ``ljust`` Left-aligns the value in a field of a given width **Argument:** field size ``lower`` Converts a string into all lowercase ``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. ``phone2numeric`` Takes a phone number and converts it in to its numerical equivalent ``pluralize`` Returns 's' if the value is not 1, for '1 vote' vs. '2 votes' ``pprint`` A wrapper around pprint.pprint -- for debugging, really ``random`` Returns a random item from the list ``removetags`` Removes a space separated list of [X]HTML tags from the output ``rjust`` Right-aligns the value in a field of a given width **Argument:** field size ``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. ``slugify`` Converts to lowercase, removes non-alpha chars and converts spaces to hyphens ``stringformat`` Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formating syntax, with the exception that the leading "%" is dropped. See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting ``striptags`` Strips all [X]HTML tags ``time`` Formats a time according to the given format (same as the ``now`` tag). ``timesince`` Formats a date as the time since that date (i.e. "4 days, 6 hours") ``title`` Converts a string into titlecase ``truncatewords`` Truncates a string after a certain number of words **Argument:** Number of words to truncate after ``unordered_list`` Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing