The sign-up screen says By continuing, you agree to the Terms and Privacy Policy, and two of those words have to be tappable. The quickest way to build that is three or four strings: a prefix, a link label, a conjunction, another link label, and a period. English looks right. German does not, because the verb particle belongs at the end of the sentence and your layout has no slot for it. Japanese wants the links before the verb. Arabic reverses the whole run.
A localized string with a link has to stay one sentence. This guide shows how to keep each styled or linked sentence as a single translatable message on Android Views, Jetpack Compose, SwiftUI, and React, how to attach behavior without counting characters, how to pass user values safely, and how to stop a broken tag from reaching production.
The short answer
Put the whole sentence in one message. Mark the styled run inside that message with a named slot that a translator can move: an Android <annotation> span, a Markdown link or emphasis in an Apple localized string, or a named rich text tag in react-i18next or FormatJS. Keep URLs and click handlers in code and bind them to the slot name. Escape every argument before a markup parser sees it. Then add a check that fails the build when a translation loses or reshapes a tag.
Why splitting the sentence breaks
Splitting feels harmless because each fragment translates cleanly in isolation. The problem is the order you glue them back together. Our guide on why app localization needs message formatting covers the general case: concatenation hard-codes English grammar into code. Styled text is the version of that mistake that survives code review, because the split looks like a rendering requirement rather than a grammar decision.
Take the consent line. An illustrative German translation reads roughly Wenn du fortfährst, stimmst du den Nutzungsbedingungen und der Datenschutzerklärung zu. The two links land in the middle, the articles change case, and zu closes the sentence. Four English fragments cannot express that. Translators who receive Terms and Privacy Policy as standalone keys also lose the context they need to pick the right case.
The web libraries document the same rule. The react-i18next Trans component "keeps markup and links inside one translatable sentence", and FormatJS rich text formatting supports tags inside a message "so sentences don't have to be broken up into chunks." Android and Apple offer the same idea through different syntax.
Keep the boundary inside the translation
Once the sentence is one string, the next temptation is to find the link in code. Some teams search for the word Terms and wrap whatever they find. Others store a start index and a length. Both fail as soon as the text changes language.
A practitioner report on Stack Overflow shows the offset version: a developer placed a ClickableSpan by index in a translated string and got an index-out-of-bounds exception in French because the French string was shorter than the English one. The search version fails more quietly. The English word does not exist in the German string, so nothing becomes tappable and nobody notices until a user asks how to read the terms.
Never locate a styled or tappable run by character offset or by searching for the English word; put the span boundary inside the translated string so translators move it with the words. Every platform below gives you a way to do that, and every one of them lets the translator decide where the run starts and ends in their own grammar, including right-to-left scripts where an offset counted from the left edge is meaningless.
Android views use annotations instead of offsets
The Android string resources guide supports a short list of HTML tags such as <b>, <i>, <u>, and <font> directly in strings.xml, and it documents a separate pattern for translated styling: define an <annotation> tag in each locale's strings.xml so translators preserve the annotation wherever it lands in the sentence, then read the string with getText() and walk its Annotation spans.
<!-- values/strings.xml -->
<string name="consent">By continuing, you agree to the <annotation link="terms">Terms</annotation> and <annotation link="privacy">Privacy Policy</annotation>.</string>
<!-- values-de/strings.xml -->
<string name="consent">Wenn du fortfährst, stimmst du den <annotation link="terms">Nutzungsbedingungen</annotation> und der <annotation link="privacy">Datenschutzerklärung</annotation> zu.</string>
The annotation value is a stable slot name, not a URL. Code maps the slot to behavior:
val source = resources.getText(R.string.consent)
val spanned = source as? Spanned ?: SpannedString(source)
val result = SpannableString(spanned)
for (a in spanned.getSpans(0, spanned.length, android.text.Annotation::class.java)) {
if (a.key != "link") continue
val target = a.value
result.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) = openLegalPage(target)
}, spanned.getSpanStart(a), spanned.getSpanEnd(a), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
consentView.text = result
consentView.movementMethod = LinkMovementMethod.getInstance()
Two rules keep this safe. Read with getText(), because the plain getString() path returns a String without spans. And treat an unknown slot value as a bug that your checks catch, not something to guess at runtime.
Compose converts spans into link annotations
Compose text is an AnnotatedString, and you cannot add a modifier to part of a Text. The Compose guide on enabling user interactions in text uses LinkAnnotation to make a run clickable. Its examples build the string with buildAnnotatedString and append, which is fine for one language but brings back the fragment problem if you append translated pieces.
The string resources guide notes that Compose code reading complex <annotation> tags must retrieve the string as a legacy Spanned with getText() and convert the spans into an AnnotatedString. A small adapter does that once for the whole app:
@Composable
fun annotatedResource(@StringRes id: Int, links: Map<String, String>): AnnotatedString {
val source = LocalContext.current.resources.getText(id)
val spanned = source as? Spanned ?: return AnnotatedString(source.toString())
return buildAnnotatedString {
append(spanned.toString())
for (a in spanned.getSpans(0, spanned.length, android.text.Annotation::class.java)) {
val url = links[a.value] ?: continue
addLink(LinkAnnotation.Url(url), spanned.getSpanStart(a), spanned.getSpanEnd(a))
}
}
}
The adapter takes the whole translated sentence and only adds link ranges where the translator put the annotation. The URL map stays in code, so a translator cannot point the legal link at the wrong page.
Arguments and markup do not mix by default
Greetings and notices often need a bold run around a value: Welcome back, **Ana**. Values inside a styled run cause the second trap. Formatting arguments and markup fight each other: Android getString and stringResource strip styling, and any user-supplied argument must be escaped before an HTML or Markdown parser sees it.
The Android guide says formatting methods such as stringResource() strip all style information. A Stack Overflow question about arguments in a styled string resource describes the same dead end with Views: getText() keeps the bold but takes no arguments, while getString() takes arguments and drops the bold. The documented workaround is to store the tags as escaped HTML, format first, and parse afterward:
<string name="welcome_back">Welcome back, <b>%1$s</b>.</string>
val safeName = TextUtils.htmlEncode(displayName)
val html = stringResource(R.string.welcome_back, safeName)
Text(AnnotatedString.fromHtml(html))
Escape every argument. The same guide says that because fromHtml() processes all HTML entities, you should escape any HTML characters in the values you format into the string with TextUtils.htmlEncode(). Without it, a display name that contains < or & changes the markup of your sentence. The bug lives in your formatting code and only appears for users whose names contain those characters.
The same reasoning applies to Markdown, and here it is a recommendation rather than a documented platform rule. If code builds a Markdown string by inserting user text and then parses the result, square brackets and asterisks in that text become formatting or links. Escape the inserted value first, or keep it as a separate argument the parser never reads as markup.
SwiftUI and AttributedString
Apple's AttributedString documentation says localized strings loaded with initializers such as init(localized:) can contain Markdown for styling, and that these initializers can apply a replacementIndex attribute so you can find replacement values whose order varies between languages. The SwiftUI Text documentation adds that a text view built from an AttributedString can use Markdown to style runs, with string attributes taking priority over view modifiers.
So the catalog entry can carry the styled run:
// String Catalog, key "consent.line"
// en: "By continuing, you agree to the [Terms](app-legal:terms) and [Privacy Policy](app-legal:privacy)."
// de: "Wenn du fortfährst, stimmst du den [Nutzungsbedingungen](app-legal:terms) und der [Datenschutzerklärung](app-legal:privacy) zu."
Text("consent.line")
.environment(\.openURL, OpenURLAction { url in
guard url.scheme == "app-legal" else { return .systemAction }
openLegalPage(url.host() ?? url.path())
return .handled
})
The link destinations are slot names in a private scheme, not real URLs, which keeps the translator out of routing. Apple does not require this pattern; it is our recommendation.
Which initializer you call decides whether localization and Markdown run at all. Apple's LocalizedStringKey documentation explains that SwiftUI creates a LocalizedStringKey when you pass a string literal, and that passing a String variable to the matching initializer avoids localization. A Stack Overflow report on SwiftUI Markdown with a dynamic string shows the visible symptom: the same Markdown link renders from a literal but appears unrendered when it arrives in a String variable. If keys come from a table, a server, or a helper, wrap them explicitly with Text(LocalizedStringKey(key)) or build an AttributedString(localized:) value, so localization and Markdown parsing both run.
Named tags in one message on the web
On the web, keep the message whole and let the framework attach components to named tags. With react-i18next:
<Trans
i18nKey="consent"
components={{ terms: <a href={TERMS_URL} />, privacy: <a href={PRIVACY_URL} /> }}
/>
// en.json: "consent": "By continuing, you agree to the <terms>Terms</terms> and <privacy>Privacy Policy</privacy>."
The react-i18next docs recommend this named-components form over the older indexed <0> and <1> tags, and they warn that existing self-closing HTML tag names such as link, img, and media are reserved and will not work as component keys. Most teams try link first, so pick slot names such as terms or helpPage instead. The docs also note that indexed tags are hard for translators, since an index moved to the wrong place breaks the sentence and a spreadsheet gives no hint what element 0 is.
FormatJS takes the same approach with handler functions per tag. A practitioner question on interpolating a link in the middle of a react-i18next sentence shows why: the asker did not want URLs hard-coded in label files, and named components solve exactly that. Other vendors' docs, such as Linguana's guide to dynamic text and links, describe the same split of responsibility: the application owns the destination and behavior, and the translation controls where the linked words appear.
Make tag parity a release gate
Translators and machine translation both handle markup imperfectly. A tag gets dropped, renamed to match a translated word, or closed in the wrong order. The impact depends on the runtime. A GitHub issue in the Lingui project describes translators mistyping variables, forgetting to close tags, or changing tag order and nesting, after which the production build threw an exception and the page did not render.
Treat tags as part of the string contract and fail the build when a translation drops, renames, or misnests a tag, because some runtimes throw instead of degrading gracefully. The check is small enough to run on every pull request and every translation import:
import re
TAG = re.compile(r"<(/?)([A-Za-z][\w-]*)(?:\s[^>]*)?>")
def tag_tree(message):
stack, seen = [], []
for match in TAG.finditer(message):
closing, name = match.group(1) == "/", match.group(2)
if closing:
if not stack or stack.pop() != name:
raise ValueError(f"misnested </{name}>")
else:
stack.append(name)
seen.append((name, len(stack)))
if stack:
raise ValueError(f"unclosed <{stack[-1]}>")
return sorted(seen)
def check(source, translation):
if tag_tree(source) != tag_tree(translation):
raise ValueError("tag set or nesting differs from source")
The comparison uses sorted tag names with their depth, so translators may reorder sibling tags, which they must be free to do, but may not add, drop, rename, or re-nest them. Run the same idea on Android annotations by comparing the set of link values, and on Markdown by comparing link destinations. If your pipeline translates strings with i18nAgent or any other tool, run this check after translation and before the strings merge.
Verify every shipped language
A passing parity check proves the structure survived. Behavior needs its own checks in each shipped locale:
- Render the consent and greeting screens and confirm every expected run is styled or tappable. A missing link is easy to miss in a screenshot, so assert it in UI tests where your framework exposes link ranges.
- Tap each link and confirm it opens the right destination for the slot name, not the first link in the sentence.
- Test with a display name that contains
<,&,*, and[to prove arguments are escaped. - Check right-to-left locales such as Arabic and Hebrew for correct link placement and punctuation.
- Turn on TalkBack and VoiceOver and confirm each link is reachable and announced with its translated label. This check is our recommendation; the platforms do not guarantee how links are announced.
- Run pseudo-localization so expanded text shows whether a link wraps awkwardly across lines.
Common mistakes
- Splitting the sentence because one run needs a different color. Put a span inside the message instead of adding a new key.
- Searching for the English word or storing offsets to place a link. Both break in other languages.
- Reading an Android string with
getString()and wondering why the bold disappeared. - Putting real URLs in translation files, which lets a translation change routing and makes link updates a translation job.
- Naming a react-i18next component
link, which is a reserved self-closing tag name. - Passing a SwiftUI key as a
Stringvariable and shipping raw Markdown. - Shipping translations without a tag-parity check and finding the broken nesting from a crash report.
What to do next
Search your codebase for sentence fragments that sit next to a link or bold run: keys ending in _prefix, _suffix, _link, or _part1, and code that calls indexOf on translated text. Pick the sign-up consent line first, convert it to one message with a named slot on each platform, add the tag-parity check to CI, and run the verification list in your two most different locales before converting the rest.
