potpy.template – Template module

Module Contents

class potpy.template.Template(template, **type_converters)[source]

A simple string template class.

Allows you to match against a string, extracting a dictionary of template parameters, with optional parameter type conversion. An example template:

>>> t = Template('Hello my name is {name}!')

Using the match() method, you can extract information from a string:

>>> t.match('Hello my name is David!')
{'name': 'David'}

>>> t.match('This string does not match.')

Parameter type conversion allows you to coerce parameters to Python types:

>>> t = Template('The answer is {answer}', answer=int)
>>> t.match('The answer is 42')
{'answer': 42}

You can also specify a regex in your parameter spec to further refine matches:

>>> t = Template('/posts/{post_id:\d+}', post_id=int)
>>> t.match('/posts/37')
{'post_id': 37}
>>> t.match('/posts/foo')

The reverse of matching is filling. Use the fill() method to insert information into your template string:

>>> t = Template('The answer is {answer}')
>>> t.fill(answer=42)
'The answer is 42'
fill(**kwargs)[source]

Fill a template string with the given parameters.

>>> Template('The answer is {answer}').fill(answer=42)
'The answer is 42'
match(string)[source]

Match a string against the template.

If the string matches the template, return a dict mapping template parameter names to converted values, otherwise return None.

>>> t = Template('Hello my name is {name}!')
>>> t.match('Hello my name is David!')
{'name': 'David'}
>>> t.match('This string does not match.')

Project Versions

Table Of Contents

Previous topic

potpy.router – Router module

Next topic

potpy.wsgi – WSGI module

This Page