From 19cfae39af4e7cbb8a0719e64d619ba0248f9d76 Mon Sep 17 00:00:00 2001 From: Martin Kagamino Lehoux Date: Tue, 12 May 2026 17:12:07 +0200 Subject: ki18n: derive language from request context via strategy chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) (limited to 'README.md') diff --git a/README.md b/README.md index fc63e0d..ce2d349 100644 --- a/README.md +++ b/README.md @@ -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 `/*.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 -- cgit v1.3