Login

Variable inspect filter

Author:
buriy
Posted:
May 6, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

This module has two template filters allowing you to dump any template variable. Special handling for object instances. Pretty output.

Usage: {% load dumper %} ... <pre>{{ var|rawdump }}</pre> or {% load dumper %} ... {{ var2|dump }}

How to install: As usual, put into <your-proj>/<any-app>/templatetags/dumper.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django import template
from django.template.defaultfilters import linebreaksbr
from django.utils.html import escape
try:
    from django.utils.safestring import mark_safe
except ImportError: # v0.96 and 0.97-pre-autoescaping compat
    def mark_safe(x): return x
from pprint import pformat

def rawdump(x):
    if hasattr(x, '__dict__'):
        d = {
            '__str__':str(x),
            '__unicode__':unicode(x),
            '__repr__':repr(x),
        }
        d.update(x.__dict__)
        x = d
    output = pformat(x)+'\n'
    return output

def dump(x):
    return mark_safe(linebreaksbr(escape(rawdump(x))))

register = template.Library()
register.filter('rawdump', rawdump)
register.filter('dump', dump)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Rozza (on May 7, 2008):

Nice snippet - only change I would add is a check in to ensure that TEMPLATE_DEBUG is True

#

Please login first before commenting.