Display text with line numbers.
(value, autoescape=True)
| 230 | @register.filter(is_safe=True, needs_autoescape=True) |
| 231 | @stringfilter |
| 232 | def linenumbers(value, autoescape=True): |
| 233 | """Display text with line numbers.""" |
| 234 | lines = value.split("\n") |
| 235 | # Find the maximum width of the line count, for use with zero padding |
| 236 | # string format command |
| 237 | width = str(len(str(len(lines)))) |
| 238 | if not autoescape or isinstance(value, SafeData): |
| 239 | for i, line in enumerate(lines): |
| 240 | lines[i] = ("%0" + width + "d. %s") % (i + 1, line) |
| 241 | else: |
| 242 | for i, line in enumerate(lines): |
| 243 | lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) |
| 244 | return mark_safe("\n".join(lines)) |
| 245 | |
| 246 | |
| 247 | @register.filter(is_safe=True) |