Localization
Editors and users may want to write content in several languages. This module enables that. Your pages read one language at a time, and a missing translation falls back to the default language.
const post = await cms.findOne("posts", { where: { slug: "hallo" }, locale: "de" });
Set it up
Add the languages
Add localization to tenon.config.ts:
export default defineCms({
// ...
localization: {
locales: ["en", "de"],
defaultLocale: "en",
},
});
Localize a collection
Set localized: true on each collection or global that has translations:
import { defineCollection } from "tenoncms";
export const posts = defineCollection({
localized: true,
permalink: "/posts/{slug}",
fields: {
title: { type: "text", required: true },
slug: { type: "slug", from: "title", required: true },
// One image for every language
cover: { type: "image", localized: false },
},
});
Each field of a localized collection now has one value per language. Each language also has its own draft and publish state, so German can go live while English is still a draft. In the admin, a language menu in the top bar switches the language of the form.
localized: falseon a field shares one value across all languages.- A group, array or blocks field is localized as a whole. Fields inside it cannot set
localized. - A collection or global without
localizedstores one value and ignoreslocale. - The media library cannot be localized.
- The built-in
generalandseoglobals are localized oncelocalizationis set.
Options
localization takes these options:
["en", "de"]. MUST NOT be empty or hold duplicates.locale, and that missing values fall back to. MUST be one of locales.true.{ prefix: "except-default" }. See URLs and the language switch.localized and defaultLocale later. On the first database access after the change, Tenon moves the stored values between the shared and the per-language storage, and logs each move.Read a locale
Pass locale to any read. Without it, reads use defaultLocale:
// German, with English where German has no value
await cms.find("posts", { locale: "de" });
// Only posts that are published in German, with German values only
await cms.find("posts", { locale: "de", fallback: false });
With fallback, the default, a read fills the gaps from the default language:
- A field without a value in the requested language returns the default language's value.
- A document that is published only in the default language still shows.
wherematches the value the read returns, so a filter onslugfinds the English slug when German has none.
Without fallback, a document shows only when it is published in the requested language, and missing values are null.
- An unknown locale throws a
ValidationError, or answers400over HTTP. populateloads related documents in the same language.- Documents of a localized collection have
locale, the language of the read, andlocales, the languages that have a version. - Over HTTP, use
?locale=de&fallback=false.
Write a locale
Writes take locale too. Without it, they write the default language:
await cms.update("posts", id, { title: "Hallo Welt" }, { locale: "de" });
await cms.publish("posts", id, { locale: "de" });
A write in one language changes the shared fields for all languages. copyLocale() and removeLocale() copy and delete translations. See Languages in the local API.
Lists in every language
A localized group, array or blocks field keeps the same items in every language by default: the same blocks, in the same order. Only the values inside the items are translated.
When an editor adds, moves or removes a block in German, the English page changes too. The new block shows the default language's values until someone translates it.
To give each language its own lists, set syncStructure: false on the collection or global:
export const pages = defineCollection({
localized: true,
syncStructure: false,
fields: {
// ...
},
});
Editors can also switch it per document, in the "…" menu of the form under Sync Content Structure.
URLs and the language switch
routing puts the language into the URL as a prefix:
routing | English | German |
|---|---|---|
{ prefix: "except-default" } (default) | /about | /de/about |
{ prefix: "always" } | /en/about | /de/about |
false | your routes | your routes |
- Write
permalinkwithout the language. Tenon adds the prefix, so/posts/{slug}becomes/de/posts/hallo. - With
routing: false, apermalinkMAY use{locale}, like/{locale}/posts/{slug}. - Your routes MUST serve the prefixed URLs.
alternates: true adds the URL of each published translation to a document:
const post = await cms.findOne("posts", {
where: { slug: "hallo" },
locale: "de",
alternates: true,
});
// { en: "/posts/hello", de: "/de/posts/hallo", "x-default": "/posts/hello" }
post?.alternates;
Use it for the language switch and for hreflang tags. It needs a permalink on the collection. The head components of Pages and SEO render the hreflang tags from it.
switchTarget(localization, path, locale, alternates) from tenoncms/client returns where a language link leads: the translation in that language, or that language's homepage when there is none.
Per framework
The integration's middleware sets Astro.locals.locale and Astro.locals.path, the path without the prefix. A [...locale] folder serves both /posts/hello and /de/posts/hallo:
---
import LocaleSwitch from "../../../components/LocaleSwitch.astro";
export const prerender = false;
const { tenon, locale, path } = Astro.locals;
const slug = Astro.params.slug!;
// An unknown prefix stays in `path`, so `/xx/posts/hello` is a 404.
const post =
path === `/posts/${slug}`
? await tenon.findOne("posts", { where: { slug }, locale, alternates: true })
: undefined;
if (!post) return new Response(null, { status: 404 });
---
<html lang={locale}>
<body>
<LocaleSwitch alternates={post.alternates} />
<h1>{post.title}</h1>
</body>
</html>
useTenon() reads in the route's language. useLocale() returns the language helpers:
locales,defaultLocaleandlocale, the language of the route.path, the route's path without the prefix.localePath(path, locale?)adds the prefix to a path.switchLocalePath(locale)returns the URL of the page in another language.
An optional [[locale]] folder serves both /posts/hello and /de/posts/hallo:
<script setup lang="ts">
const route = useRoute();
const { path } = useLocale();
const slug = computed(() => String(route.params.slug));
const { data: post } = await useTenon().findOne(
"posts",
() => ({ where: { slug: slug.value }, alternates: true }) as const,
);
// An unknown prefix stays in `path`, so `/xx/posts/hello` is a 404.
if (!post.value || path.value !== `/posts/${slug.value}`) throw createError({ statusCode: 404 });
useAlternates(() => post.value?.alternates);
</script>
<template>
<h1>{{ post?.title }}</h1>
</template>
useAlternates() hands the translations to switchLocalePath(). useTenonSeo(post) does the same, and adds the hreflang tags. The language switch can then live in any component.
There is no adapter for languages. Read the language from the URL with localeFromPath() and cms.localization in a server function:
import { createServerFn } from "@tanstack/react-start";
import { localeFromPath, type Locale } from "tenoncms/client";
import cms from "../../tenon.config";
const getPage = createServerFn()
.validator((url: string) => url)
.handler(async ({ data: url }) => {
// "/de/about" is { locale: "de", path: "/about" }
const { locale, path } = localeFromPath(url, cms.localization!);
const page = await cms.findOne("pages", {
where: { path },
locale: locale as Locale<typeof cms>,
alternates: true,
});
return { page, localization: cms.localization! };
});
Browser code cannot import tenon.config.ts, so the server function also returns cms.localization. The language switch and localizePath(path, locale, localization), which adds the prefix to other links, need it.
Build a language switch
A language switch links to the current page in each language. switchTarget() picks the translation from the page's alternates, or that language's homepage when there is none:
---
import { switchTarget } from "tenoncms/client";
interface Props {
alternates?: Record<string, string>;
}
const { tenon, locale, path } = Astro.locals;
const localization = tenon.localization!;
---
<nav aria-label="Language">
{localization.locales.map((code) =>
code === locale ? (
<strong>{code}</strong>
) : (
<a href={switchTarget(localization, path, code, Astro.props.alternates)} hreflang={code}>
{code}
</a>
),
)}
</nav>
<script setup lang="ts">
const { locales, locale, switchLocalePath } = useLocale();
// `locales` holds plain strings, and `switchLocalePath()` takes a locale of your config.
type Code = Parameters<typeof switchLocalePath>[0];
</script>
<template>
<nav aria-label="Language">
<template v-for="code in locales" :key="code">
<strong v-if="code === locale">{{ code }}</strong>
<NuxtLink v-else :to="switchLocalePath(code as Code)" :hreflang="code">{{ code }}</NuxtLink>
</template>
</nav>
</template>
import { useLocation } from "@tanstack/react-router";
import { localeFromPath, switchTarget, type Localization } from "tenoncms/client";
type Props = {
localization: Localization;
alternates?: Record<string, string>;
};
export function LocaleSwitch({ localization, alternates }: Props) {
const { locale, path } = localeFromPath(useLocation().pathname, localization);
return (
<nav aria-label="Language">
{localization.locales.map((code) =>
code === locale ? (
<strong key={code}>{code}</strong>
) : (
<a key={code} href={switchTarget(localization, path, code, alternates)} hrefLang={code}>
{code}
</a>
),
)}
</nav>
);
}
The current language shows as text, the others as links. hreflang tells browsers and search engines the language of each link.
alternates, like <LocaleSwitch alternates={post.alternates} />. A layout can take them as a prop and pass them on. On a page without a document, leave them out.<LocaleSwitch /> in any component, like the layout. It reads the translations that the page hands to useAlternates() or useTenonSeo().Pass localization and the page's alternates from the loader:
function Page() {
const { page, localization } = Route.useLoaderData();
return <LocaleSwitch localization={localization} alternates={page?.alternates} />;
}
Site strings
Short texts in your templates, like "Read more", need translations too. The strings preset turns them into a localized global with defaults in code:
import { stringsPreset } from "tenoncms/presets";
export default defineCms({
// ...
presets: [stringsPreset({ readMore: { en: "Read more", de: "Weiterlesen" } })],
});
Read it with fallback: false, so each language gets its own default:
const strings = await cms.getGlobal("strings", { locale: "de", fallback: false });
Related resources
- Strings: translated interface texts.
- Pages and SEO:
hreflangand canonical tags. - Reading: all read options.