+class TemplateValidator(formencode.FancyValidator):
+ def to_python(self, value, state=None):
+ """Takes a template, like u'{{Color|red|text=Any text}}' and translates it to a Python tuple
+ (title, anonym_params, named_params) where title is the template title,
+ anonym_params is a list of anonymous parameters and named_params is a OrderedDict
+ of named parameters. Whitespace of the parameters is stripped."""
+ if not value.startswith(u'{{'):
+ raise formencode.Invalid(u'Template does not start with "{{"', value, state)
+ if not value.endswith(u'}}'):
+ raise formencode.Invalid(u'Template does not end with "}}"', value, state)
+ parts = value[2:-2].split(u'|')
+
+ # template name
+ title = parts[0].strip()
+ if len(title) == 0:
+ raise formencode.Invalid(u'Empty template tilte.', value, state)
+ del parts[0]
+
+ # anonymous parameters
+ anonym_params = []
+ while len(parts) > 0:
+ equalsign_pos = parts[0].find(u'=')
+ if equalsign_pos >= 0: break # named parameter
+ anonym_params.append(parts[0].strip())
+ del parts[0]
+
+ # named or numbered parameters
+ named_params = collections.OrderedDict()
+ while len(parts) > 0:
+ equalsign_pos = parts[0].find(u'=')
+ if equalsign_pos < 0:
+ raise formencode.Invalid(u'Anonymous parameter after named parameter.', value, state)
+ key, sep, value = parts[0].partition(u'=')
+ key = key.strip()
+ if len(key) == 0:
+ raise formencode.Invalid(u'Empty key.', value, state)
+ if named_params.has_key(key):
+ raise formencode.Invalid(u'Duplicate key: "{0}"'.format(key), value, state)
+ named_params[key] = value.strip()
+ del parts[0]
+
+ return title, anonym_params, named_params
+
+