Author: SmileyChris Date: 2011-05-19 19:42:28 -0700 (Thu, 19 May 2011) New Revision: 16251
Modified: django/trunk/docs/howto/custom-template-tags.txt Log: Fixes #15732 -- better introduction of template filter decorator concepts (first register, then stringfilter). Thanks for the patch, hahasee. Modified: django/trunk/docs/howto/custom-template-tags.txt =================================================================== --- django/trunk/docs/howto/custom-template-tags.txt 2011-05-20 02:14:30 UTC (rev 16250) +++ django/trunk/docs/howto/custom-template-tags.txt 2011-05-20 02:42:28 UTC (rev 16251) @@ -105,23 +105,6 @@ "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 @@ 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 ~~~~~~~~~~~~~~~~~~~~~~~~~ -- You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-updates@googlegroups.com. To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-updates?hl=en.