Custom template tags and filters

Django's template language comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. Nevertheless, you may find yourself needing functionality that is not covered by the core set of template primitives.

You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.

Writing custom template filters

Custom filters are just Python functions that take one or two arguments:

  • The value of the variable (input)-not necessarily a string.
  • The value of the argument-this can have a default value, or be left out altogether.

For example, in the filter {{ var|foo:"bar" }}, the ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.