Skip to content

Instantly share code, notes, and snippets.

@rbarrois
Created September 29, 2013 20:58
Show Gist options
  • Save rbarrois/6756478 to your computer and use it in GitHub Desktop.
Save rbarrois/6756478 to your computer and use it in GitHub Desktop.
Helper to get pretty (?) exceptions in Django templates for invalid variable names.
class InvalidStringHandler(object):
"""Custom handler for invalid string in templates."""
def __call__(self):
"""Force crashes in {{ foo|sth }}, without breaking __str__."""
import ipdb; ipdb.set_trace()
raise ValueError()
def __nonzero__(self):
"""So that '{% if foo %}' doesn't break."""
return False
def __contains__(self, key):
"""There is a test for '%s' in TEMPLATE_STRING_IF_INVALID."""
return key == '%s'
def __mod__(self, var):
"""Handles TEMPLATE_STRING_IF_INVALID % var"""
raise ValueError("Undefined template variable %r" % var)
TEMPLATE_STRING_IF_INVALID = InvalidStringHandler()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment