Sub topic 8
Dynamic content and templates
This chapter assumes you have read the earlier chapters on segmentation approaches and can read basic Python. You should also know that each customer carries a segment label (for example lapsed or loyal) and a set of profile fields such as first name. Here we cover how a template turns those inputs into one message per customer.
What dynamic content is
Dynamic content is a message whose parts change depending on who receives it. You write the message once as a template. At send time, a rendering engine fills in the template for each recipient. The engine takes two inputs: the template and a context. The context is the data about that one customer, such as a name, a segment and a product list.
This lets you send a million emails from one template and still show different text, offers and images to different people.
Dynamic content has three common uses:
- Substitution puts a value into the text, such as a first name or a loyalty balance.
- Conditional blocks show or hide text depending on a rule, such as the customer's segment.
- Repeating blocks loop over a list, such as the items left in a basket.
The segments from earlier chapters decide which branch of the template a person sees. The template itself holds no model logic. That separation keeps content writers and data scientists from blocking each other.
The render pipeline
A render pipeline has four steps: load the customer context, choose the template or branch, render it, and check the result before sending.
The validation step is the one teams skip, and it causes most visible failures. A template can render without errors and still produce text like Hi , we saved your basket. Validation catches that kind of output before a customer sees it.
A first template
The example below uses Jinja2, a widely used Python template engine. It renders one template differently by segment and supplies a default when the first name is missing.
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. Three pieces of syntax matter:
{{ ... }}is an expression. The engine replaces it with the value.{% ... %}is a statement. It controls flow, such asifandfor, and prints nothing itself.| default('there', true)is a filter. A filter transforms a value.
The second argument to `default`
The true in default('there', true) matters. Without it, Jinja2 applies the default only when the variable is undefined, meaning the key is absent. A key that exists with the value None or an empty string "" would pass through unchanged. With true, the default applies to any falsy value (None, "", 0, False).
Real customer data often contains a key set to None or an empty string, because a form field was left blank or a database column allows nulls. So the true form is usually the one you want for text fields.
Be careful with numeric fields. A loyalty balance of 0 is falsy, so default('unknown', true) would replace a real zero with "unknown". For numbers, test for None explicitly:
from jinja2 import Template
balance_template = Template(
"{% if points is none %}Join our rewards programme."
"{% else %}You have {{ points }} points.{% endif %}"
)
print(balance_template.render(points=0))
print(balance_template.render(points=None))The first call prints You have 0 points. The second prints Join our rewards programme.
Looping over a list
Repeating blocks display things like recommended products. The loop should handle an empty list, because a customer may have no basket items or no recommendations.
from jinja2 import Template
basket_template = Template(
"{% for item in items[:3] %}"
"- {{ item.name }}: {{ '%.2f' | format(item.price) }}\n"
"{% else %}"
"Browse our best sellers.\n"
"{% endfor %}"
)
print(basket_template.render(items=[
{"name": "Trail shoes", "price": 89.0},
{"name": "Wool socks", "price": 12.5},
]))
print(basket_template.render(items=[]))Two details are worth noting. The slice items[:3] caps the list at three entries, so a customer with fifty items does not get an enormous email. The {% else %} clause on a for loop runs only when the loop had no items, which gives you a built-in empty state.
Choosing the template with the segment
There are two common ways to vary content by segment.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Conditionals inside one template | One file holds `if` branches for every segment | Easy to see all variants together | The file grows, and branches get hard to review |
| One template per segment | A lookup maps segment to template name | Each template stays short and can be reviewed alone | Shared parts, such as the footer, can drift apart |
For two or three segments, conditionals inside one template are fine. Past that, use a lookup table from segment to template, and put shared parts in modules. The next chapter covers modules in detail.
A lookup should always have a default entry:
TEMPLATES = {
"lapsed": "lapsed_winback.html",
"loyal": "loyal_thanks.html",
}
DEFAULT_TEMPLATE = "general_newsletter.html"
def pick_template(segment):
return TEMPLATES.get(segment, DEFAULT_TEMPLATE)
print(pick_template("lapsed"))
print(pick_template("brand_new_segment"))A segment added by the data team next month will not be in the dictionary yet. The default means those customers still receive a sensible message instead of an error.
Strict undefined variables
By default, Jinja2 treats a misspelled variable as an empty value. If your template says {{ firstname }} but the context key is first_name, the output silently contains a blank. In testing, you want this to fail loudly. Use StrictUndefined:
from jinja2 import Template, StrictUndefined
from jinja2.exceptions import UndefinedError
strict = Template("Hi {{ firstname }}", undefined=StrictUndefined)
try:
strict.render(first_name="Ana")
except UndefinedError as error:
print("Caught:", error)Use strict mode in tests and in a pre-send check. In production, a fallback message is usually better than failing a whole batch, so decide deliberately how each environment should behave.
Common errors
- Blank fields. Missing,
Noneand empty values produce gaps such asHi ,. Fix this with defaults on every personal field. - Wrong default for zero. Using the
trueform ofdefaulton numbers hides real zeros. - Unescaped HTML. If a customer name contains
<or&, it can break an HTML email or inject markup. Useautoescapefor HTML templates, and never mark user-supplied values as safe. - Awkward grammar. "You have 1 items" looks careless. Handle singular and plural with a condition.
- Stale segment labels. A template can only be as current as the label it receives. If labels refresh weekly, a customer who just bought may still get a "we saved your basket" message.
- Sensitive inferences. A template that says "Because you searched for ..." can reveal more than the customer expects. Keep the wording consistent with the consent rules from earlier chapters.
Previewing and testing templates
Treat templates like code. A small test set catches most failures before a send.
- Build a set of test contexts: a full profile, a profile with a missing first name, a profile with an empty list, and a profile with a segment the lookup does not know.
- Render every template against every context.
- Fail the check if the output contains unresolved markers such as
{{, the literal textNone, or a double space left by an empty value. - Review rendered samples from each segment by eye. Automated checks do not notice a tone problem.
The sketch below applies step 3 to a rendered string:
def looks_broken(text):
bad_markers = ["{{", "}}", "{%", "None", "undefined"]
return any(marker in text for marker in bad_markers) or ", " in text
print(looks_broken("Hi there, we saved your basket."))
print(looks_broken("Hi None, we saved your basket."))The first call returns False and the second returns True. Marker checks are crude. A customer whose real name contains the text "None" would be flagged, so treat a flag as a reason to look at the message, not as proof of a bug.
Where decisions belong
Keep three layers apart:
- The segment says who the customer is, and comes from rules, clusters or predictions.
- The template says how the message looks and reads for that segment.
- The decision logic says which content to pick when several candidates fit. Later chapters cover this with rules, next best action and bandits.
When these mix, changes become risky. Embedding a complicated offer decision inside an if chain in a template makes it untestable and hard to hand to a writer. Keep templates simple, and let a separate step pick the content.
Exercise
A template uses {{ points | default('none', true) }}. A customer has points = 0. What does the message show, and how would you change the template so that it shows 0?
Show answer
It shows none, because the true argument applies the default to any falsy value and 0 is falsy. Remove the true so the default applies only to undefined values, and make sure missing data is not stored as None. Or, more robustly, test explicitly: {% if points is none %}none{% else %}{{ points }}{% endif %}.
Exercise
Your segment lookup maps lapsed and loyal to templates. The data team adds a new segment called high_value, and the send job crashes for those customers. What was missing from the design, and what would you add?
Show answer
The lookup had no default template. Use TEMPLATES.get(segment, DEFAULT_TEMPLATE) so unknown segments get a general message. Also add a pre-send test that renders every segment label in the current segment list, so a new label without a template is caught before the send.