diff options
| author | Martin Kagamino Lehoux <martin@lehoux.net> | 2026-05-12 17:12:07 +0200 |
|---|---|---|
| committer | Martin Kagamino Lehoux <martin@lehoux.net> | 2026-05-12 17:12:07 +0200 |
| commit | 19cfae39af4e7cbb8a0719e64d619ba0248f9d76 (patch) | |
| tree | af289634fac81e78ebe92029062eb13016622b8a /README.md | |
| parent | 783028348a17803ba2e0d2745229d57c0626a464 (diff) | |
ki18n: derive language from request context via strategy chain
Replace Tr(lang, ...) with Tr(ctx, ...) — language is now resolved once
per request by LangMiddleware and stored in context. Callers no longer
need to thread a lang string through to templates.
Adds Strategy interface with CookieStrategy and AcceptLanguageStrategy
built-ins; middleware chains them in order, falling back to en-GB.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 37 |
1 files changed, 31 insertions, 6 deletions
@@ -15,15 +15,40 @@ ## ki18n -- [ ] Document - [ ] Add gettext to CI - [ ] Add time handling -- [ ] Use request data for default lang -1. `go run github.com/martinlehoux/kagamigo/cmd/gettext -write` -2. Use `Tr("key", value...)` in you templ files -3. Complete generated files -4. Run +### Setup + +1. Call `ki18n.Init(localesFS)` at startup with a filesystem containing `<lang>/*.yml` translation files. +2. Register `ki18n.LangMiddleware(...)` on your router, passing one or more strategies in priority order. +3. Run `go run github.com/martinlehoux/kagamigo/cmd/gettext -write` to generate translation files. +4. Complete the generated files. + +### Language detection strategies + +```go +// Detect from a cookie named "lang", then fall back to Accept-Language header +ki18n.LangMiddleware( + ki18n.CookieStrategy("lang"), + ki18n.AcceptLanguageStrategy, +) +``` + +Built-in strategies: +- `ki18n.CookieStrategy(name string)` — reads the named cookie +- `ki18n.AcceptLanguageStrategy` — parses the `Accept-Language` request header + +If no strategy resolves a language, the middleware falls back to `en-GB`. + +### Translating in templ files + +```go +// ctx is the context passed to your templ component +@ki18n.Tr(ctx, "Hello %s", userName) +``` + +If the key is not found in the resolved language, the format string itself is returned. ## web |
