i18n

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package i18n translates the interface (t()/formatPlural()): source strings are English, catalogs give their translations per language. A lookup goes down a chain - the active theme's catalog, then the engine's, then the modules' - and falls back to the source string itself.

Catalog file (JSON, one per language):

{
  "strings": {
    "Save": "Speichern",
    "@count view": ["@count Aufruf", "@count Aufrufe"]
  },
  "contexts": {
    "Long month name": {"May": "Mai"}
  }
}

A plural entry is keyed by the singular source string and holds one form per plural category of the language (PluralIndex).

Placeholders: @name - the value HTML-escaped; %name - escaped and wrapped in <em class="placeholder">; :name - a URL (unsafe schemes dropped, non-ASCII percent-encoded, then escaped). @count in plural strings is the number.

Index

Constants

View Source
const SourceLanguage = "en"

SourceLanguage - the language of the source strings.

Variables

This section is empty.

Functions

func CheckTranslation

func CheckTranslation(source, text string) error

CheckTranslation - whether text may stand for source: it keeps every placeholder of the source (@count may go - a plural form may spell the number out) and has no HTML but the source's own tags, as they are (a translation is output as HTML, unescaped); a "<" or ">" a browser takes for text is text.

func Default

func Default() string

Default - the site's default language.

func DirFS

func DirFS(dir string) fs.FS

DirFS - a catalog directory on disk (nil when it doesn't exist).

func ErrorText

func ErrorText(ctx context.Context, err error) string

ErrorText - err's message for the user in the request's language: the translation of an Error anywhere in err's chain; any other error gets a message of its own - its text (paths, queries, addresses) is for the log, not for visitors.

func Errorf

func Errorf(source string, args ...any) error

Errorf - an Error with placeholders, for messages a service returns to be shown to the user: i18n.Errorf("User @name already exists.", "@name", name).

func Format

func Format(text string, args ...any) string

Format fills the @name/%name/:name placeholders in text from args (name/value pairs) for HTML: values escaped, %name wrapped in <em class="placeholder">.

func FormatText

func FormatText(text string, args ...any) string

FormatText fills the placeholders as plain text (values as is).

func FromContext

func FromContext(ctx context.Context) string

FromContext - the request's language, else the site's default.

func IsUserError

func IsUserError(err error) bool

IsUserError - whether err carries a message for the user (an Error in its chain): a check the input failed rather than a failure of the site.

func JSScript

func JSScript(lang string) []byte

JSScript - the script served at /i18n/<lang>.js: the translations of the JS strings in lang (window.kosatkaTranslations) and the runtime (Kosatka.t, Kosatka.tc, Kosatka.formatPlural). Like Go's T, the functions return plain text: placeholder values are not escaped.

func JSVersion

func JSVersion(lang string) string

JSVersion - a short hash of JSScript(lang), for a cache-busting URL.

func N

func N(source string) string

N marks source as an interface string without translating it (like gettext_noop): for labels kept in data - maps, struct fields, defaults - and translated where shown, with T(ctx, label) or {{t .Label}}. cmd/i18n-extract finds i18n.N("…") like i18n.T.

func NC

func NC(msgctx, source string) string

NC - N with a message context: i18n.NC("Abbreviated month name", "May").

func NativeName

func NativeName(code string) string

NativeName - the language's name in the language itself ("Deutsch"); the code for one it doesn't know.

func Plural

func Plural(ctx context.Context, count int, singular, plural string, args ...any) string

Plural - Translator.PluralText in the request's language.

func PluralCategories

func PluralCategories(lang string) []string

PluralCategories - the CLDR plural categories lang uses for whole numbers, in CLDR order (zero, one, two, few, many, other): the order of a plural entry's forms in its catalog ("one", "few", "many" for Russian; "one", "other" for English).

func PluralIndex

func PluralIndex(lang string, count int) int

PluralIndex - the plural form index of count in lang: its CLDR plural category's place among the categories lang uses for whole numbers (PluralCategories) - Russian 1 / 2-4 / 5+ (with 11-14), Polish, Czech, French and the rest by their own CLDR rules.

func SetDefault

func SetDefault(lang string)

SetDefault makes lang the site's default language (from the site settings).

func SetJSKeys

func SetJSKeys(keys []JSKey)

SetJSKeys sets the strings the JavaScript translates; the per-language scripts (JSScript) are rebuilt on next use.

func SetTranslator

func SetTranslator(t *Translator)

SetTranslator makes t the site's translator.

func T

func T(ctx context.Context, source string, args ...any) string

T - source in the request's language as plain text, for Go code (Translator.Text with the site's translator); escaped where output.

func TC

func TC(ctx context.Context, msgctx, source string, args ...any) string

TC - T with a context (msgctxt), for strings that read differently in different places.

func WithLang

func WithLang(ctx context.Context, lang string) context.Context

WithLang - ctx carrying lang as the request's language.

Types

type Entry

type Entry struct {
	Lang, Context, Source string
	Text                  string
	Forms                 []string
}

Entry - a translation kept outside the catalog files (a site's own or a downloaded one, in its database): its language, context and source, its text or its plural forms (keyed by the singular source, as in a catalog).

func ParseCatalog

func ParseCatalog(lang string, b []byte) ([]Entry, error)

ParseCatalog - the entries of a catalog file (a <lang>.json) of lang, sorted by context and source.

type Error

type Error struct {
	Source string
	Args   []any
}

Error - an error whose message is an interface string: Error() is the English text (logs), ErrorText translates it for the user.

func (*Error) Error

func (e *Error) Error() string

type JSKey

type JSKey struct {
	Context string
	Source  string
}

JSKey - a string the site's JavaScript translates with Kosatka.t, Kosatka.tc or Kosatka.formatPlural (found at startup by internal/i18nextract.ExtractJS).

type LanguageOption

type LanguageOption struct {
	Code  string
	Label string
}

LanguageOption - a language for a select: its code and native name.

func KnownLanguages

func KnownLanguages() []LanguageOption

KnownLanguages - the languages it has names for, by code: what a site's content may be in (its interface - only Options').

type Source

type Source struct {
	Context string `json:"context,omitempty"`
	Source  string `json:"source"`
	Plural  string `json:"plural,omitempty"`
	Module  string `json:"module,omitempty"`
	Theme   string `json:"theme,omitempty"`
	Starter bool   `json:"starter,omitempty"`
}

Source - an interface string of the code (the source strings' list, translations/sources): its context, source (a plural string's singular, its catalog key) and plural form, and whose it is - the engine's, a module's or a theme's. Starter - a text only a new site's starter content has: written once, in the site's language, as its data (a language pack translates it; it isn't the interface's).

func CatalogSources

func CatalogSources(dir fs.FS) ([]Source, error)

CatalogSources - the strings the catalogs of dir (<lang>.json files) translate, each once: the strings of a theme or module the sources list hasn't (Plural unknown; a plural entry's forms tell it).

func ParseSources

func ParseSources(b []byte) ([]Source, error)

ParseSources - the source strings' list (JSON).

type TranslationError

type TranslationError struct {
	Placeholder string
	Tag         string
}

TranslationError - why a translation can't stand for its source: a placeholder of the source it drops (Placeholder), or HTML the source doesn't have (Tag; "<" - a tag not closed).

func (*TranslationError) Error

func (e *TranslationError) Error() string

type Translator

type Translator struct {
	// contains filtered or unexported fields
}

Translator - the catalogs of every language, in lookup order (the theme's first, then the engine's, then the modules', then the downloaded ones - WithPacks), and the site's own translations over them (WithSite).

func Current

func Current() *Translator

Current - the site's translator.

func Load

func Load(dirs ...fs.FS) (*Translator, error)

Load builds a Translator from catalog directories in lookup order (e.g. the theme's, the engine's, the modules'): each holds <lang>.json files; a missing directory is skipped.

func (*Translator) Available

func (t *Translator) Available(lang string) bool

Available - lang is one of Options.

func (*Translator) Default

func (t *Translator) Default(lang, ctx, source string) (string, []string, bool)

Default - the translation of source (in context ctx) to lang by the catalogs alone, the site's own left out: its text or plural forms; false - none.

func (*Translator) Has

func (t *Translator) Has(lang, ctx, source string) bool

Has - source (in context ctx) has a translation for lang.

func (*Translator) Languages

func (t *Translator) Languages() []string

Languages - the languages with a catalog, sorted.

func (*Translator) Options

func (t *Translator) Options() []LanguageOption

Options - the languages the interface can be shown in: the source language and every language with a catalog.

func (*Translator) Plural

func (t *Translator) Plural(lang, ctx string, count int, singular, plural string, args ...any) string

Plural - the form of singular/plural for count in lang: the catalog's forms of singular (PluralIndex), else the English source forms. @count is count; args as for T. The result is HTML.

func (*Translator) PluralText

func (t *Translator) PluralText(lang, ctx string, count int, singular, plural string, args ...any) string

PluralText - Plural as plain text (see Text).

func (*Translator) Site

func (t *Translator) Site(lang, ctx, source string) (string, []string, bool)

Site - the site's own translation of source to lang (WithSite).

func (*Translator) T

func (t *Translator) T(lang, ctx, source string, args ...any) string

T - source translated to lang, placeholders filled from args (name/value pairs: "@name", value, …). The result is HTML (values are escaped; the catalogs are trusted) - for templates.

func (*Translator) Text

func (t *Translator) Text(lang, ctx, source string, args ...any) string

Text - T as plain text: values are not escaped, %name is not wrapped - for Go code, whose strings are escaped where they are output.

func (*Translator) WithPacks

func (t *Translator) WithPacks(entries []Entry) *Translator

WithPacks - t with the downloaded translations (packs) as the last catalog of their languages: a copy, t is left as it is. A pack is of a language the built-in catalogs don't have, so for it the theme's catalog comes first and the pack after it.

func (*Translator) WithSite

func (t *Translator) WithSite(entries []Entry) *Translator

WithSite - t with the site's own translations over its catalogs: a copy, t is left as it is. A source the site rewords in English (SourceLanguage) reads so in a language that doesn't translate it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL