Working with Content

Localization

Content in several languages, with URLs and fallbacks.

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:

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:

cms/collections/posts.ts
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: false on 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 localized stores one value and ignores locale.
  • The media library cannot be localized.
  • The built-in general and seo globals are localized once localization is set.

Options

localization takes these options:

The language codes of the site, like ["en", "de"]. MUST NOT be empty or hold duplicates.The language that reads use without a locale, and that missing values fall back to. MUST be one of locales.Whether a missing value or translation reads as the default language's. Default true.How URLs carry the language. Default { prefix: "except-default" }. See URLs and the language switch.
You can change 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.
  • where matches the value the read returns, so a filter on slug finds 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 answers 400 over HTTP.
  • populate loads related documents in the same language.
  • Documents of a localized collection have locale, the language of the read, and locales, 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:

routingEnglishGerman
{ prefix: "except-default" } (default)/about/de/about
{ prefix: "always" }/en/about/de/about
falseyour routesyour routes
  • Write permalink without the language. Tenon adds the prefix, so /posts/{slug} becomes /de/posts/hallo.
  • With routing: false, a permalink MAY 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:

src/pages/[...locale]/posts/[slug].astro
---
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>

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>

The current language shows as text, the others as links. hreflang tells browsers and search engines the language of each link.

Pass the page's 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.

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:

tenon.config.ts
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 });