Templating
A very frequent need when showing text to users is to generate it dynamically depending on the state of the software.
Typically, this leads to code like this:
name = 'Alessandro' messages = ['Message 1', 'Message 2'] txt = 'Hello %s, You have %s message' % (name, len(messages)) if len(messages) > 1: txt += 's' txt += ':n' for msg in messages: txt += msg + 'n' print(txt)
This makes it very hard to foresee the upcoming structure of the message and it's also very hard to maintain in the long term. To generate text, it's usually more convenient to reverse the approach and instead of putting text in code, we shall put code in text. That's exactly what template engines do and, while the standard library has very complete solutions for formatting, it lacks a template engine out of the box, but it can easily be extended to make one.
How to do it...
The steps for this recipe are:
- The
string.Formatter
object allows you to extend its syntax, so we can specialize it to support injecting...