package phrasebook_test import ( "context" "fmt" "testing/fstest" "git.golem15.com/golem15/summercms/modules/phrasebook" "git.golem15.com/golem15/summercms/modules/towel" ) // langFS stands in for the plugin's embedded lang directory. var langFS = fstest.MapFS{ "lang/en/posts.yaml": {Data: []byte(`title: Posts greeting: "Hello, :name" shout: "Welcome, :NAME" count: one: ":count post" other: ":count posts" drafts: "{0} No drafts|{1} One draft|[2,*] :count drafts" `)}, "lang/pl/posts.yaml": {Data: []byte(`title: Posty count: one: ":count post" few: ":count posty" many: ":count postów" other: ":count posta" `)}, } func ExampleTranslator_Get() { cat := phrasebook.NewCatalog() if err := cat.Load("acme.blog", langFS); err != nil { fmt.Println(err) return } tr := phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"}) // surf stores the request locale on the context; here the example does. ctx := towel.WithLocale(context.Background(), "pl") fmt.Println(tr.Get(ctx, "acme.blog::posts.title", nil)) // pl has no greeting, so the fallback locale answers. fmt.Println(tr.Get(ctx, "acme.blog::posts.greeting", map[string]string{"name": "Ada"})) fmt.Println(tr.GetIn("en", "acme.blog::posts.shout", map[string]string{"name": "Ada"})) // A missing key comes back as the key. fmt.Println(tr.Get(ctx, "acme.blog::posts.missing", nil)) // Output: // Posty // Hello, Ada // Welcome, ADA // acme.blog::posts.missing } func ExampleTranslator_Choice() { cat := phrasebook.NewCatalog() if err := cat.Load("acme.blog", langFS); err != nil { fmt.Println(err) return } tr := phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"}) for _, n := range []int{1, 3, 5, 22} { fmt.Println(tr.ChoiceIn("pl", "acme.blog::posts.count", n, nil)) } fmt.Println(tr.ChoiceIn("en", "acme.blog::posts.count", 5, nil)) for _, n := range []int{0, 1, 7} { fmt.Println(tr.ChoiceIn("en", "acme.blog::posts.drafts", n, nil)) } // Output: // 1 post // 3 posty // 5 postów // 22 posty // 5 posts // No drafts // One draft // 7 drafts }