Ticket #15732: 15732_stringfilter_docs.diff

File 15732_stringfilter_docs.diff, 1.8 KB (added by hahasee, 13 years ago)
  • docs/howto/custom-template-tags.txt

     
    105105        "Converts a string into all lowercase"
    106106        return value.lower()
    107107
    108 Template filters that expect strings
    109 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    110 
    111 If you're writing a template filter that only expects a string as the first
    112 argument, you should use the decorator ``stringfilter``. This will
    113 convert an object to its string value before being passed to your function::
    114 
    115     from django.template.defaultfilters import stringfilter
    116 
    117     @stringfilter
    118     def lower(value):
    119         return value.lower()
    120 
    121 This way, you'll be able to pass, say, an integer to this filter, and it
    122 won't cause an ``AttributeError`` (because integers don't have ``lower()``
    123 methods).
    124 
    125108Registering custom filters
    126109~~~~~~~~~~~~~~~~~~~~~~~~~~
    127110
     
    152135If you leave off the ``name`` argument, as in the second example above, Django
    153136will use the function's name as the filter name.
    154137
     138Template filters that expect strings
     139~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     140
     141If you're writing a template filter that only expects a string as the first
     142argument, you should use the decorator ``stringfilter``. This will
     143convert an object to its string value before being passed to your function::
     144
     145    from django.template.defaultfilters import stringfilter
     146    from django import template
     147
     148    register = template.Library()
     149
     150    @register.filter
     151    @stringfilter
     152    def lower(value):
     153        return value.lower()
     154
     155This way, you'll be able to pass, say, an integer to this filter, and it
     156won't cause an ``AttributeError`` (because integers don't have ``lower()``
     157methods).
     158
    155159Filters and auto-escaping
    156160~~~~~~~~~~~~~~~~~~~~~~~~~
    157161
Back to Top