Sub topic 9
Modular content and safe fallbacks
This chapter assumes you have read the previous chapter on dynamic content and templates. You should know how a template inserts values such as a first name, and how a condition changes the text. You should also be comfortable reading short Python scripts and working with tabular customer data.
Templates alone do not scale well. Once a campaign has twenty segments and five channels, a single large template turns into a tangle of conditions that nobody dares to edit. Modular content solves this by splitting a message into small, reusable blocks. Safe fallbacks make sure that every block still produces something sensible when data is missing or a segment is unknown.
Why modules instead of one big template
A content module is a self-contained block of a message, such as a header, a hero image with a headline, a product row, or a call to action. Each module has an identifier, a set of inputs it needs, and one or more variants. A message is then assembled from a list of modules chosen for the recipient.
This gives you several benefits:
- Reuse. The same "free delivery" banner can appear in an email, an app screen, and a web page.
- Independent testing. You can test two headlines without touching the rest of the message.
- Safer edits. A change to the footer cannot break the product row.
- Clear ownership. Brand, legal, and campaign teams can each own different modules.
The cost is extra structure. You need a catalogue of modules, naming rules, and a way to check that modules fit together visually. For a small programme with three segments, a single template is often simpler. Move to modules when the number of combinations (segments times channels times message types) starts to outgrow what one person can review.
The anatomy of a module
A useful module definition records more than the text. At minimum, track the following.
| Field | Purpose | Example |
|---|---|---|
| `module_id` | Stable name used in logs and reports | `hero_winback` |
| `slot` | Where the module may be placed | `hero`, `body`, `footer` |
| `required_fields` | Customer data the module needs | `first_name`, `last_basket_item` |
| `eligible_segments` | Who may see it | `lapsed`, `new` |
| `channels` | Where it can render | `email`, `push` |
| `fallback` | What to use if inputs are missing | `hero_generic` |
| `expires_on` | Date after which it must not be sent | `2026-12-31` |
The required_fields and fallback entries are what make a module safe. The system can check them before rendering instead of discovering a problem after a message has gone out.
Layers of fallback
A fallback is the content used when the preferred content cannot be shown. Think of fallbacks in layers, from most specific to most general.
- Field-level fallback. A single missing value is replaced by a default, for example "there" instead of an empty first name.
- Module-level fallback. If a module cannot render because required data is missing, a simpler variant of that module is used.
- Segment-level fallback. If the customer has no segment, or the segment is stale, the message uses the default audience content.
- Message-level fallback. If assembly fails entirely, the system sends a known-good generic message or sends nothing.
The last layer deserves thought. For a marketing email, sending nothing is usually better than sending a broken message. For a transactional message such as a password reset, you must send the generic version, because the customer needs it.
Field-level defaults in a template
The previous chapter showed the Jinja default filter. There is one detail that causes many bugs. By default, the filter only replaces values that are undefined. A value of None or an empty string counts as defined, so it passes through. Passing true as the second argument tells Jinja to also replace any value that evaluates as false.
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"))
print(template.render(first_name="", segment="new"))
print(template.render(segment="new"))All three calls produce a greeting with "there". Without the true, the first two calls would print "Hi None," and "Hi ,".
A default is not always the right choice. Some values cannot be defaulted safely. A product name, a price, or a discount percentage that is missing should make the whole module fall back, because "Get 0% off" or "Your item: " is worse than a generic offer.
Validating before you render
Rather than relying on the template to cope, check the inputs first. The function below decides whether a module can render, and otherwise walks down its fallback chain.
from jinja2 import Template
MODULES = {
"hero_winback": {
"template": "We saved your {{ last_basket_item }}, {{ first_name }}.",
"required": ["first_name", "last_basket_item"],
"fallback": "hero_generic",
},
"hero_generic": {
"template": "See what is new this week.",
"required": [],
"fallback": None,
},
}
def is_present(value):
if value is None:
return False
if isinstance(value, str) and not value.strip():
return False
return True
def render_module(module_id, customer, max_depth=5):
"""Render a module, following the fallback chain. Return (module_id_used, text)."""
current = module_id
for _ in range(max_depth):
module = MODULES[current]
if all(is_present(customer.get(field)) for field in module["required"]):
return current, Template(module["template"]).render(**customer)
if module["fallback"] is None:
break
current = module["fallback"]
raise ValueError(f"No renderable module for {module_id}")
customers = [
{"first_name": "Ana", "last_basket_item": "running shoes"},
{"first_name": "Ben", "last_basket_item": None},
{"first_name": "", "last_basket_item": "backpack"},
]
for customer in customers:
used, text = render_module("hero_winback", customer)
print(used, "->", text)Running this prints the personalised hero for Ana and the generic hero for the other two. The function returns which module was actually used. That detail matters later, because your reporting must record what the customer saw, not what you intended to show.
The max_depth guard prevents an infinite loop if someone accidentally configures a fallback cycle, such as A falling back to B and B back to A. Better still, check for cycles when modules are published.
Fallbacks and the quality of your data
Heavy use of fallbacks can hide a data problem. If 40% of customers silently receive the generic hero because last_basket_item is empty, your personalisation is not doing what the plan says it does. Treat fallback rate as a metric.
Track at least:
- The share of renders served by each module, split by whether it was the first choice or a fallback.
- The fallback rate per required field, so you can see which data source is failing.
- The fallback rate per segment, because a segment with poor data coverage may be systematically underserved.
A sudden jump in fallback rate usually means a data pipeline broke, for example a renamed column upstream. Set an alert threshold, and decide in advance whether the send should pause or continue with generic content when the threshold is crossed.
Edge cases to plan for
- Stale data. A field can be present but wrong. A "last viewed item" from eighteen months ago is technically available. Add a freshness rule, such as ignoring the value if it is older than 30 days, and treat it as missing.
- Out-of-stock or expired items. A product module should check inventory and offer dates at render time, not at campaign build time. Use
expires_onand a stock check as part of the eligibility test. - Content that does not fit. A long product name can break an email layout or overflow a push notification. Define maximum lengths per slot and truncate or fall back to a shorter variant.
- Sensitive inferences. A module that says "Because you searched for ..." may reveal something a customer did not expect to be used, especially on shared devices. Mark such modules with a stricter eligibility rule tied to consent, and give them a neutral fallback.
- Channel differences. A module that works in email may not exist in SMS. If the module has no variant for the channel, the system should skip the slot, not render an email block in a text message.
- Conflicting modules. Two modules in the same message may each promote a different discount. Add a rule that limits one offer module per message.
Assembling a message from slots
Message assembly can be treated as a loop over slots. For each slot, the decision layer picks a module, the renderer produces text, and the fallback logic fills any gap. A simple layout definition keeps the order and the required slots explicit.
LAYOUT = [
{"slot": "hero", "required": True},
{"slot": "body", "required": True},
{"slot": "footer", "required": True},
{"slot": "cross_sell", "required": False},
]
def assemble(layout, choices, customer):
parts, log = [], []
for item in layout:
module_id = choices.get(item["slot"])
if module_id is None:
if item["required"]:
raise ValueError(f"Missing required slot: {item['slot']}")
continue
used, text = render_module(module_id, customer)
parts.append(text)
log.append({"slot": item["slot"], "chosen": module_id, "used": used})
return "\n".join(parts), logOptional slots are dropped when empty, and required slots fail loudly so that the message-level fallback can take over. The log list records both the chosen and the used module for every slot, which gives you the fallback metrics described above.
Governance of the module library
A module library needs housekeeping, or it fills with stale and conflicting content.
- Give each module an owner and a review date.
- Retire modules by expiry date and do not rely on someone remembering to remove them.
- Require a fallback for every module that has required fields, and test that the chain ends in a module with no required fields.
- Keep a preview tool that renders every module against a set of awkward test customers: missing name, very long name, no history, non-Latin characters, and no consent.
Exercise
A hero module needs first_name and last_basket_item. In production, 35% of lapsed customers receive the generic hero. Name two things you would check before deciding the personalised hero is a poor idea, and one change that would stop the problem from being hidden in your reports.
Show answer
First, check why the fields are missing: look at the fallback rate per required field to see whether last_basket_item is the main cause, and check for a pipeline failure or a data coverage gap rather than a content problem. Second, check whether stale-data rules are discarding values that were once valid, such as an item older than the freshness limit. To stop the problem being hidden, log both the chosen module and the module actually used for every send, and report lift only for customers who received the personalised version, alongside the fallback rate, so generic sends do not dilute the measured effect.
Exercise
Why does {{ first_name | default('there') }} still print "Hi None" when first_name is None, and how do you fix it?
Show answer
The default filter only replaces undefined variables. None is a defined value, so it passes through. Add true as the second argument, default('there', true), so that any false value, including None and an empty string, is replaced.