Sub topic 6
Templates and localization
This chapter assumes you know the pipeline from the earlier chapters: producers emit events, workers pick them up, and each channel worker hands a message to a provider. You should also be comfortable reading short Python snippets. Here we cover how a worker turns an event into the text a user sees, in the right language and format for each channel.
Why separate content from events
An event such as order_shipped should describe what happened. It should not contain the sentence shown to the user. Keeping the two apart gives you three benefits:
- Producers stay simple. The shipping service sends
order_id, not a translated paragraph. - Copywriters and translators can change wording without a code deploy.
- One event can produce different content per channel: a 60-character push title, a 160-character SMS, and an HTML email.
The event's type field, which you already use for preference lookup, is also the key for finding the template. The payload supplies the variables.
The rendering step
Rendering happens in the channel worker, after the preference check and before the provider call. Rendering late means a template fix applies to messages still waiting in the queue. It also keeps queue messages small.
Template storage and lookup
Key each template by three parts: notification type, channel, and locale. Add a version number so you can roll out changes and roll them back.
| Part | Example | Reason |
|---|---|---|
| Type | `order_shipped` | Matches the event |
| Channel | `push`, `sms`, `email`, `in_app` | Each channel has different format and size limits |
| Locale | `en`, `pt-BR` | Language and regional variant |
| Version | `3` | Safe rollout and rollback |
Small systems can keep templates in files shipped with the service. Larger ones store them in a database or a content service with caching, so non-engineers can edit them through a review workflow.
A minimal renderer
This example uses only the standard library. It resolves a locale with fallback, escapes values for email, and fails loudly when a variable is missing.
from html import escape
from string import Template
DEFAULT_LOCALE = "en"
TEMPLATES = {
("order_shipped", "push", "en"): Template("Order $order_id is on its way."),
("order_shipped", "push", "es"): Template("Tu pedido $order_id está en camino."),
("order_shipped", "email", "en"): Template("<p>Hi $name, order <b>$order_id</b> has shipped.</p>"),
}
class TemplateError(Exception):
"""A permanent failure. Retrying will not fix a missing template or variable."""
def resolve_locale(requested, available, default=DEFAULT_LOCALE):
for candidate in (requested, requested.split("-")[0], default):
if candidate in available:
return candidate
raise TemplateError(f"no template for locale {requested!r} or default")
def render(notification_type, channel, locale, payload):
available = {
loc for (t, c, loc) in TEMPLATES if t == notification_type and c == channel
}
chosen = resolve_locale(locale, available)
template = TEMPLATES[(notification_type, channel, chosen)]
values = payload
if channel == "email":
values = {k: escape(str(v)) for k, v in payload.items()}
try:
return template.substitute(values)
except KeyError as exc:
raise TemplateError(f"missing variable {exc}") from exc
print(render("order_shipped", "push", "es-MX", {"order_id": "A-77"}))
print(render("order_shipped", "email", "en", {"order_id": "A-77", "name": "<Ana>"}))The first call asks for es-MX. No such template exists, so the resolver tries es and finds the Spanish one. The second call shows escaping: <Ana> becomes <Ana>, so a user-supplied name cannot inject markup into an email.
Fallback chains
A fallback chain decides what happens when a translation is missing. A typical chain is the exact locale (pt-BR), then the language (pt), then the product default. Never skip the last step. A message in the default language is better than no message, though for legal or security notices you may prefer to block the send and alert the content team.
Plurals, dates and numbers
Naive string substitution breaks on grammar. "1 items" looks careless, and plural rules differ by language. English has two forms. Polish has three in this example.
PLURAL_RULES = {
"en": lambda n: "one" if n == 1 else "other",
"pl": lambda n: (
"one" if n == 1
else "few" if n % 10 in (2, 3, 4) and n % 100 not in (12, 13, 14)
else "many"
),
}
MESSAGES = {
("en", "one"): "{n} new message",
("en", "other"): "{n} new messages",
("pl", "one"): "{n} nowa wiadomość",
("pl", "few"): "{n} nowe wiadomości",
("pl", "many"): "{n} nowych wiadomości",
}
def unread_text(locale, n):
form = PLURAL_RULES[locale](n)
return MESSAGES[(locale, form)].format(n=n)
for count in (1, 3, 5):
print(unread_text("pl", count))Hand-written rules only illustrate the idea. In production, use a library built on CLDR data, the shared Unicode database of locale rules. Examples are Babel for Python, or ICU MessageFormat, which many translation tools understand.
Apply the same principle to dates, times, currency and numbers. Put raw values in the payload, such as a UTC timestamp and an amount with its currency code. Format them at render time using the user's locale and time zone. Pre-formatted strings from the producer cannot adapt to the recipient.
Channel constraints
Each channel needs its own template, not a shared string.
- Push: Short title and body. Platforms truncate long text, and the visible length varies by device.
- SMS: A single message holds 160 characters in the GSM-7 alphabet. One non-GSM character, such as an emoji or many accented letters, switches the message to UCS-2, which cuts the limit to 70. Longer text is split into several billed segments.
- Email: Subject, HTML body, and a plain-text alternative. Escape variables in HTML.
- In-app: Often structured data, such as a title, body and deep link, that the client renders itself.
Common errors
- Failing on a missing variable by retrying. A missing variable is a permanent error. Send it to a dead-letter queue and alert. Retrying only wastes capacity.
- Defaulting silently to empty strings. A message reading "Hi , your order shipped" is worse than a failed send. Use strict substitution, as above.
- Skipping escaping. User-controlled values such as names and product titles must be escaped for HTML email. Treat them as untrusted.
- Using locale from the wrong place. Store the user's preferred locale in their profile or preferences. Do not infer it from the request that triggered the event, which may come from a system job or another user.
- Concatenating fragments. Building a sentence from translated pieces breaks word order in other languages. Translate whole sentences with placeholders.
- Unversioned edits. Editing a live template without a version makes rollback and audit hard.
- Rendering at ingestion time. If you render before queuing, a long queue delay can deliver stale text or a wrong time zone. Render at send time.
Testing templates
Test every template against sample payloads in every supported locale. A simple CI check can render all combinations and fail on missing variables, unresolved placeholders, or over-length output. Also keep a preview tool so translators can see real output per channel.
Exercise
A German SMS template renders correctly for an English test but a user in Germany receives it split into three billed segments. Name two likely causes and one process change to catch them.
Show answer
Likely causes: the German text is longer than the English source, and it contains characters outside the GSM-7 alphabet, which switches the message to UCS-2 with a 70-character limit. A process change is to render every template in every supported locale in CI and fail the build when the output exceeds the channel's length budget, counting the encoding.