python__django_tutorials/docs/ch4-optimizing.md

2.4 KiB

Chapter 4: optimizing and debugging templates

To re-enable templates, reset settings.py#TEMPLATES[APP_DIRS] = True.

Beware: anything in DIRS has priority over APP_DIRS.

Inheritance

A layout template contains {% block <name> %} ... {% endblock %} elements.

These will be replaced in templates inheriting it, which start with {% extends "applayout.html" %}, and proceed to provide values for the blocks present in the layout.

To create a dark mode:

  • copy the style.css to style-dark.css
  • copy the applayout.html to applayout-dark.html

Tags

  • Comments:
    • <!-- ... -->: HTML comments, not displayed but present in output
    • {# ... #}}: single-line comments, removed from output
    • {% comment <label> #}} ... {% endcomment %}: multi-line comments, removed from output
  • debugging
    • {% debug %} a bit like Twig {% dump %} but more data
    • in layout: lots of global info, no page content
    • in template outside blocks: nothing
    • in template in a block: block content, then same general info
    • output is not escaped and contains `<' so may be unreadable outside source view
  • pipelines:
    • {{ <value> | <filter> }}
    • example: {{ ticket.created_at | date:"D, d M Y" }}
  • custom filters: functions taking one value and returning one
    • create a <app>/templatetags/ folder
    • add empty <app>/templatetags/__init__.py to mark as a package
    • add tag file <app>/templatetags/mytags.py
from django import template

register = template.Library()
time_format = '%A, %B %d, %Y at %I:%M%p'
time_format_mil = '%A, %B %d, %Y at %H%M'


def mydate(oldvalue, miltime=False):
    if miltime: return oldvalue.strftime(time_format_mil)
    return oldvalue.strftime(time_format)


register.filter('mydate', mydate)
  • add {% load mytags %} to the template.
    • It may be necessary to restart the server
  • use as {{ ticket.created_at | mydate }}

Troubleshooting

Read the page, assuming DEBUG is True

Template backends

Alternate engines exist, the most visible being Jinja2:

  • most of the same features
  • extra performance
  • some extras
  • extra complexity
  • different syntax (but closer to Twig)

Enabling Jinja2:

  • install Jinja2 with pip
  • add a new entry in the settings.py#TEMPLATES array:
{
    'BACKEND': 'django.template.backends.jinja2.Jinja2',
    'DIRS': ['./ticketing/templates/jinja2'],
},