Parse TemplateTag Variables Safely

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.template import Variable, VariableDoesNotExist

QUOTED_STRING = re.compile(r'^["\'](?P<noquotes>.+)["\']$')

def handle_var(self, value, context):
  stringval = QUOTED_STRING.search(value)
  if stringval:
    return stringval.group('noquotes')
  else:
    try:    
      return Variable(value).resolve(context)
    except VariableDoesNotExist:
      return value

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.