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 | | |
| 138 | Template filters that expect strings |
| 139 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 140 | |
| 141 | If you're writing a template filter that only expects a string as the first |
| 142 | argument, you should use the decorator ``stringfilter``. This will |
| 143 | convert 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 | |
| 155 | This way, you'll be able to pass, say, an integer to this filter, and it |
| 156 | won't cause an ``AttributeError`` (because integers don't have ``lower()`` |
| 157 | methods). |
| 158 | |