Skip to content

Commit

Permalink
Page context handling in i18n
Browse files Browse the repository at this point in the history
This is a workaround. We need to improve on this, but not today.

Fixes #10782
  • Loading branch information
bep committed Mar 4, 2023
1 parent ec1c97e commit 6c798eb
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 9 deletions.
3 changes: 2 additions & 1 deletion deps/deps.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package deps

import (
"context"
"fmt"
"path/filepath"
"strings"
Expand Down Expand Up @@ -71,7 +72,7 @@ type Deps struct {
FileCaches filecache.Caches

// The translation func to use
Translate func(translationID string, templateData any) string `json:"-"`
Translate func(ctx context.Context, translationID string, templateData any) string `json:"-"`

// The language in use. TODO(bep) consolidate with site
Language *langs.Language
Expand Down
18 changes: 15 additions & 3 deletions langs/i18n/i18n.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package i18n

import (
"context"
"fmt"
"reflect"
"strings"
Expand All @@ -24,11 +25,12 @@ import (
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/resources/page"

"github.com/gohugoio/go-i18n/v2/i18n"
)

type translateFunc func(translationID string, templateData any) string
type translateFunc func(ctx context.Context, translationID string, templateData any) string

var i18nWarningLogger = helpers.NewDistinctErrorLogger()

Expand Down Expand Up @@ -58,7 +60,7 @@ func (t Translator) Func(lang string) translateFunc {
}

t.logger.Infoln("i18n not initialized; if you need string translations, check that you have a bundle in /i18n that matches the site language or the default language.")
return func(translationID string, args any) string {
return func(ctx context.Context, translationID string, args any) string {
return ""
}
}
Expand All @@ -71,7 +73,7 @@ func (t Translator) initFuncs(bndl *i18n.Bundle) {
// This may be pt-BR; make it case insensitive.
currentLangKey := strings.ToLower(strings.TrimPrefix(currentLangStr, artificialLangTagPrefix))
localizer := i18n.NewLocalizer(bndl, currentLangStr)
t.translateFuncs[currentLangKey] = func(translationID string, templateData any) string {
t.translateFuncs[currentLangKey] = func(ctx context.Context, translationID string, templateData any) string {
pluralCount := getPluralCount(templateData)

if templateData != nil {
Expand All @@ -81,6 +83,16 @@ func (t Translator) initFuncs(bndl *i18n.Bundle) {
// and we keep it like this to avoid breaking
// lots of sites in the wild.
templateData = intCount(cast.ToInt(templateData))
} else {
if p, ok := templateData.(page.Page); ok {
// See issue 10782.
// The i18n has its own template handling and does not know about
// the context.Context.
// A common pattern is to pass Page to i18n, and use .ReadingTime etc.
// We need to improve this, but that requires some upstream changes.
// For now, just creata a wrepper.
templateData = page.PageWithContext{Page: p, Ctx: ctx}
}
}
}

Expand Down
8 changes: 5 additions & 3 deletions langs/i18n/i18n_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package i18n

import (
"context"
"fmt"
"path/filepath"
"testing"
Expand Down Expand Up @@ -408,9 +409,10 @@ other = "{{ . }} miesiąca"
c.Assert(d.LoadResources(), qt.IsNil)

f := tp.t.Func(test.lang)
ctx := context.Background()

for _, variant := range test.variants {
c.Assert(f(test.id, variant.Key), qt.Equals, variant.Value, qt.Commentf("input: %v", variant.Key))
c.Assert(f(ctx, test.id, variant.Key), qt.Equals, variant.Value, qt.Commentf("input: %v", variant.Key))
c.Assert(int(depsCfg.Logger.LogCounters().WarnCounter.Count()), qt.Equals, 0)
}

Expand All @@ -422,7 +424,7 @@ other = "{{ . }} miesiąca"
func doTestI18nTranslate(t testing.TB, test i18nTest, cfg config.Provider) string {
tp := prepareTranslationProvider(t, test, cfg)
f := tp.t.Func(test.lang)
return f(test.id, test.args)
return f(context.Background(), test.id, test.args)
}

type countField struct {
Expand Down Expand Up @@ -542,7 +544,7 @@ func BenchmarkI18nTranslate(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
f := tp.t.Func(test.lang)
actual := f(test.id, test.args)
actual := f(context.Background(), test.id, test.args)
if actual != test.expected {
b.Fatalf("expected %v got %v", test.expected, actual)
}
Expand Down
48 changes: 48 additions & 0 deletions langs/i18n/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,51 @@ l1: {{ i18n "l1" }}|l2: {{ i18n "l2" }}|l3: {{ i18n "l3" }}
l1: l1main|l2: l2main|l3: l3theme
`)
}

func TestPassPageToI18n(t *testing.T) {
t.Parallel()

files := `
-- config.toml --
-- content/_index.md --
---
title: "Home"
---
Duis quis irure id nisi sunt minim aliqua occaecat. Aliqua cillum labore consectetur quis culpa tempor quis non officia cupidatat in ad cillum. Velit irure pariatur nisi adipisicing officia reprehenderit commodo esse non.
Ullamco cupidatat nostrud ut reprehenderit. Consequat nisi culpa magna amet tempor velit reprehenderit. Ad minim eiusmod tempor nostrud eu aliquip consectetur commodo ut in aliqua enim. Cupidatat voluptate laborum consequat qui nulla laborum laborum aute ea culpa nulla dolor cillum veniam. Commodo esse tempor qui labore aute aliqua sint nulla do.
Ad deserunt esse nostrud labore. Amet reprehenderit fugiat nostrud eu reprehenderit sit reprehenderit minim deserunt esse id occaecat cillum. Ad qui Lorem cillum laboris ipsum anim in culpa ad dolor consectetur minim culpa.
Lorem cupidatat officia aute in eu commodo anim nulla deserunt occaecat reprehenderit dolore. Eu cupidatat reprehenderit ipsum sit laboris proident. Duis quis nulla tempor adipisicing. Adipisicing amet ad reprehenderit non mollit. Cupidatat proident tempor laborum sit ipsum adipisicing sunt magna labore. Eu irure nostrud cillum exercitation tempor proident. Laborum magna nisi consequat do sint occaecat magna incididunt.
Sit mollit amet esse dolore in labore aliquip eu duis officia incididunt. Esse veniam labore excepteur eiusmod occaecat ullamco magna sunt. Ipsum occaecat exercitation anim fugiat in amet excepteur excepteur aliquip laborum. Aliquip aliqua consequat officia sit sint amet aliqua ipsum eu veniam. Id enim quis ea in eu consequat exercitation occaecat veniam consequat anim nulla adipisicing minim. Ut duis cillum laboris duis non commodo eu aliquip tempor nisi aute do.
Ipsum nulla esse excepteur ut aliqua esse incididunt deserunt veniam dolore est laborum nisi veniam. Magna eiusmod Lorem do tempor incididunt ut aute aliquip ipsum ea laboris culpa. Occaecat do officia velit fugiat culpa eu minim magna sint occaecat sunt. Duis magna proident incididunt est cupidatat proident esse proident ut ipsum non dolor Lorem eiusmod. Officia quis irure id eu aliquip.
Duis anim elit in officia in in aliquip est. Aliquip nisi labore qui elit elit cupidatat ut labore incididunt eiusmod ipsum. Sit irure nulla non cupidatat exercitation sit culpa nisi ex dolore. Culpa nisi duis duis eiusmod commodo nulla.
Et magna aliqua amet qui mollit. Eiusmod aute ut anim ea est fugiat non nisi in laborum ullamco. Proident mollit sunt nostrud irure esse sunt eiusmod deserunt dolor. Irure aute ad magna est consequat duis cupidatat consequat. Enim tempor aute cillum quis ea do enim proident incididunt aliquip cillum tempor minim. Nulla minim tempor proident in excepteur consectetur veniam.
Exercitation tempor nulla incididunt deserunt laboris ad incididunt aliqua exercitation. Adipisicing laboris veniam aute eiusmod qui magna fugiat velit. Aute quis officia anim commodo id fugiat nostrud est. Quis ipsum amet velit adipisicing eu anim minim eu est in culpa aute. Esse in commodo irure enim proident reprehenderit ullamco in dolore aute cillum.
Irure excepteur ex occaecat ipsum laboris fugiat exercitation. Exercitation adipisicing velit excepteur eu culpa consequat exercitation dolore. In laboris aute quis qui mollit minim culpa. Magna velit ea aliquip veniam fugiat mollit veniam.
-- i18n/en.toml --
[a]
other = 'Reading time: {{ .ReadingTime }}'
-- layouts/index.html --
i18n: {{ i18n "a" . }}|
`

b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
).Build()

b.AssertFileContent("public/index.html", `
i18n: Reading time: 3|
`)
}
42 changes: 42 additions & 0 deletions resources/page/page.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,45 @@ type DeprecatedWarningPageMethods any // This was emptied in Hugo 0.93.0.
// Move here to trigger ERROR instead of WARNING.
// TODO(bep) create wrappers and put into the Page once it has some methods.
type DeprecatedErrorPageMethods any

// PageWithContext is a Page with a context.Context.
type PageWithContext struct {
Page
Ctx context.Context
}

func (p PageWithContext) Content() (any, error) {
return p.Page.Content(p.Ctx)
}

func (p PageWithContext) Plain() string {
return p.Page.Plain(p.Ctx)
}

func (p PageWithContext) PlainWords() []string {
return p.Page.PlainWords(p.Ctx)
}

func (p PageWithContext) Summary() template.HTML {
return p.Page.Summary(p.Ctx)
}

func (p PageWithContext) Truncated() bool {
return p.Page.Truncated(p.Ctx)
}

func (p PageWithContext) FuzzyWordCount() int {
return p.Page.FuzzyWordCount(p.Ctx)
}

func (p PageWithContext) WordCount() int {
return p.Page.WordCount(p.Ctx)
}

func (p PageWithContext) ReadingTime() int {
return p.Page.ReadingTime(p.Ctx)
}

func (p PageWithContext) Len() int {
return p.Page.Len(p.Ctx)
}
5 changes: 3 additions & 2 deletions tpl/lang/lang.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package lang

import (
"context"
"fmt"
"math"
"strconv"
Expand Down Expand Up @@ -45,7 +46,7 @@ type Namespace struct {
}

// Translate returns a translated string for id.
func (ns *Namespace) Translate(id any, args ...any) (string, error) {
func (ns *Namespace) Translate(ctx context.Context, id any, args ...any) (string, error) {
var templateData any

if len(args) > 0 {
Expand All @@ -60,7 +61,7 @@ func (ns *Namespace) Translate(id any, args ...any) (string, error) {
return "", nil
}

return ns.deps.Translate(sid, templateData), nil
return ns.deps.Translate(ctx, sid, templateData), nil
}

// FormatNumber formats number with the given precision for the current language.
Expand Down

0 comments on commit 6c798eb

Please sign in to comment.