+class TemplateValidator(formencode.FancyValidator):
+ def __init__(self, strip=True, as_table=False, as_table_keylen=None):
+ """Validates a MediaWiki template, e.g. {{Color|red}}
+ :param stip: If strip is True, the title, and the parameter keys and values are stripped in to_python.
+ :param as_table: formats the returned template in one row for each parameter
+ :param as_table_keylen: length of the key field for from_python. None for "automatic"."""
+ self.strip = (lambda s: s.strip()) if strip else (lambda s: s)
+ self.as_table = as_table
+ self.as_table_keylen = as_table_keylen
+
+ 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('{{'):
+ raise formencode.Invalid('Template does not start with "{{"', value, state)
+ if not value.endswith('}}'):
+ raise formencode.Invalid('Template does not end with "}}"', value, state)
+ parts = value[2:-2].split('|')
+
+ # template name
+ title = self.strip(parts[0])
+ if len(title) == 0:
+ raise formencode.Invalid('Empty template tilte.', value, state)
+ del parts[0]
+
+ # anonymous parameters
+ anonym_params = []
+ while len(parts) > 0:
+ equalsign_pos = parts[0].find('=')
+ if equalsign_pos >= 0: break # named parameter
+ anonym_params.append(self.strip(parts[0]))
+ del parts[0]
+
+ # named or numbered parameters
+ named_params = collections.OrderedDict()
+ while len(parts) > 0:
+ equalsign_pos = parts[0].find('=')
+ if equalsign_pos < 0:
+ raise formencode.Invalid('Anonymous parameter after named parameter.', value, state)
+ key, sep, value = parts[0].partition('=')
+ key = self.strip(key)
+ if len(key) == 0:
+ raise formencode.Invalid('Empty key.', value, state)
+ if key in named_params:
+ raise formencode.Invalid('Duplicate key: "{0}"'.format(key), value, state)
+ named_params[key] = self.strip(value)
+ del parts[0]
+
+ return title, anonym_params, named_params
+
+ def from_python(self, value, state=None):
+ """Formats a MediaWiki template.
+ value is a 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 dict or OrderedDict of named parameters."""
+ title, anonym_params, named_params = value
+ pipe_char, equal_char, end_char = ('\n| ', ' = ', '\n}}') if self.as_table else ('|', '=', '}}')
+ parts = ["{{" + title]
+ parts += anonym_params
+ as_table_keylen = self.as_table_keylen
+ if self.as_table and as_table_keylen is None:
+ as_table_keylen = max(list(map(len, iter(named_params.keys()))))
+ for k, v in named_params.items():
+ if self.as_table:
+ k = k.ljust(as_table_keylen)
+ parts.append((k + equal_char + v).rstrip())
+ else:
+ parts.append(k + equal_char + v)
+ return pipe_char.join(parts) + end_char
+
+