Sub topic 8
Dynamic content and templates
This chapter assumes you can read basic Python, know what a segment is (a group of customers treated alike), and have a segment label stored for each customer. Here you will turn that label into a message.
What dynamic content is
Dynamic content is a message whose parts change depending on who receives it. You write one template with placeholders and rules. A rendering step fills them in for each customer at send time.
This is how personalisation scales. Ten segments and five channels would need fifty hand-written messages. One template with a few conditions covers them all.
A template usually contains three kinds of element:
- Variables, such as a first name or a product title, which are replaced by values from the customer record.
- Conditions, such as "if the segment is lapsed, show this sentence", which choose between blocks of text.
- Filters or defaults, which transform a value or supply a substitute when it is missing.
A worked example with Jinja2
Jinja2 is a Python templating library. Its {{ ... }} syntax inserts values, and its {% ... %} syntax holds logic.
from jinja2 import Template
template = Template(
"Hi {{ first_name | default('there', true) }}, "
"{% if segment == 'lapsed' %}we saved your basket."
"{% else %}see what is new this week.{% endif %}"
)
print(template.render(first_name=None, segment="lapsed"))This prints Hi there, we saved your basket.
Two details matter here:
default('there', true)uses the substitute when the value is missing. The second argument,true, makes it also apply to values that are present but empty, such asNoneor an empty string. Without it,Nonewould print as the word "None".- The
ifblock picks the sentence from the segment, so the same template serves every segment.
How rendering flows
The template does not know where the data came from. A pipeline gathers the inputs, and the renderer combines them.
Common errors
Most template failures come from the data, not the template syntax.
| Problem | What the customer sees | Prevention |
|---|---|---|
| Missing first name | "Hi ," or "Hi None" | Use a default with `true` |
| Unknown segment value | Wrong branch, or none | Always write an `else` branch |
| Typo in a variable name | Empty gap in the text | Use strict undefined checking in testing |
| Stale data | An offer for something already bought | Check data freshness before sending |
Jinja2 hides a misspelled variable by default and prints nothing. In testing, switch to strict mode so mistakes raise an error:
from jinja2 import Environment, StrictUndefined
env = Environment(undefined=StrictUndefined)
template = env.from_string("Hi {{ first_nme }}")
try:
template.render(first_name="Ana")
except Exception as error:
print(type(error).__name__)This prints UndefinedError, which tells you the template used a name the data did not provide.
Keeping templates maintainable
Logic grows quickly. A template with many nested conditions becomes hard to review. Keep these habits:
- Put business decisions, such as which offer a segment gets, in code or a rules table. Keep the template focused on wording and layout.
- Store segment names as fixed codes, not free text, so a rename does not silently break a condition.
- Version templates and keep the previous version available for rollback.
The next chapter breaks messages into reusable modules with their own fallbacks, which keeps each template short.
Exercise
A template uses {{ firstname | default('there') }}. A customer record has firstname set to an empty string. What does the message say, and what one change fixes it?
Show answer
It says "Hi ," because without the second argument the default applies only to undefined values, not to empty ones. Change it to default('there', true) so empty values also get the substitute.
Exercise
Why should you render templates with StrictUndefined during testing?
Show answer
By default Jinja2 prints nothing for a misspelled or missing variable, so the error is silent. StrictUndefined raises an UndefinedError, so you find the mistake before customers do.