Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixes #15732 -- better introduction of template filter decorator conc…

…epts (first register, then stringfilter). Thanks for the patch, hahasee.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16251 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 803a454aefaca780d0614a8053f3bfe8a76e6876 1 parent 90e8e48
Chris Beaven SmileyChris authored
Showing with 21 additions and 19 deletions.
  1. +21 −19 docs/howto/custom-template-tags.txt
40 docs/howto/custom-template-tags.txt
View
@@ -105,23 +105,6 @@ your function. Example::
"Converts a string into all lowercase"
return value.lower()
-Template filters that expect strings
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-If you're writing a template filter that only expects a string as the first
-argument, you should use the decorator ``stringfilter``. This will
-convert an object to its string value before being passed to your function::
-
- from django.template.defaultfilters import stringfilter
-
- @stringfilter
- def lower(value):
- return value.lower()
-
-This way, you'll be able to pass, say, an integer to this filter, and it
-won't cause an ``AttributeError`` (because integers don't have ``lower()``
-methods).
-
Registering custom filters
~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -140,18 +123,37 @@ The ``Library.filter()`` method takes two arguments:
You can use ``register.filter()`` as a decorator instead::
@register.filter(name='cut')
- @stringfilter
def cut(value, arg):
return value.replace(arg, '')
@register.filter
- @stringfilter
def lower(value):
return value.lower()
If you leave off the ``name`` argument, as in the second example above, Django
will use the function's name as the filter name.
+Template filters that expect strings
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you're writing a template filter that only expects a string as the first
+argument, you should use the decorator ``stringfilter``. This will
+convert an object to its string value before being passed to your function::
+
+ from django import template
+ from django.template.defaultfilters import stringfilter
+
+ register = template.Library()
+
+ @register.filter
+ @stringfilter
+ def lower(value):
+ return value.lower()
+
+This way, you'll be able to pass, say, an integer to this filter, and it
+won't cause an ``AttributeError`` (because integers don't have ``lower()``
+methods).
+
Filters and auto-escaping
~~~~~~~~~~~~~~~~~~~~~~~~~
Please sign in to comment.
Something went wrong with that request. Please try again.