Skip to content

Commit eaca0d5

Browse files
wxiaoguangStelios Malathouras
authored andcommitted
Refactor i18n, use Locale to provide i18n/translation related functions (go-gitea#18648)
* remove unnecessary web context data fields, and unify the i18n/translation related functions to `Locale` * in development, show an error if a translation key is missing * remove the unnecessary loops `for _, lang := range translation.AllLangs()` for every request, which improves the performance slightly * use `ctx.Locale.Language()` instead of `ctx.Data["Lang"].(string)` * add more comments about how the Locale/LangType fields are used
1 parent b888d61 commit eaca0d5

31 files changed

+75
-75
lines changed

modules/context/context.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ import (
3838
"gitea.com/go-chi/session"
3939
chi "github.com/go-chi/chi/v5"
4040
"github.com/unknwon/com"
41-
"github.com/unknwon/i18n"
4241
"github.com/unrolled/render"
4342
"golang.org/x/crypto/pbkdf2"
4443
)
@@ -738,15 +737,7 @@ func Contexter() func(next http.Handler) http.Handler {
738737
ctx.Data["UnitProjectsGlobalDisabled"] = unit.TypeProjects.UnitGlobalDisabled()
739738

740739
ctx.Data["i18n"] = locale
741-
ctx.Data["Tr"] = i18n.Tr
742-
ctx.Data["Lang"] = locale.Language()
743740
ctx.Data["AllLangs"] = translation.AllLangs()
744-
for _, lang := range translation.AllLangs() {
745-
if lang.Lang == locale.Language() {
746-
ctx.Data["LangName"] = lang.Name
747-
break
748-
}
749-
}
750741

751742
next.ServeHTTP(ctx.Resp, ctx.Req)
752743

modules/translation/translation.go

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,18 @@ type Locale interface {
2525

2626
// LangType represents a lang type
2727
type LangType struct {
28-
Lang, Name string
28+
Lang, Name string // these fields are used directly in templates: {{range .AllLangs}}{{.Lang}}{{.Name}}{{end}}
2929
}
3030

3131
var (
3232
matcher language.Matcher
33-
allLangs []LangType
33+
allLangs []*LangType
34+
allLangMap map[string]*LangType
3435
supportedTags []language.Tag
3536
)
3637

3738
// AllLangs returns all supported languages sorted by name
38-
func AllLangs() []LangType {
39+
func AllLangs() []*LangType {
3940
return allLangs
4041
}
4142

@@ -81,14 +82,17 @@ func InitLocales() {
8182
}
8283
i18n.SetDefaultLang("en-US")
8384

84-
allLangs = make([]LangType, 0, i18n.Count()-1)
85+
allLangs = make([]*LangType, 0, i18n.Count())
86+
allLangMap = map[string]*LangType{}
8587
langs := i18n.ListLangs()
86-
names := i18n.ListLangDescs()
88+
descs := i18n.ListLangDescs()
8789
for i, v := range langs {
88-
allLangs = append(allLangs, LangType{v, names[i]})
90+
l := &LangType{v, descs[i]}
91+
allLangs = append(allLangs, l)
92+
allLangMap[v] = l
8993
}
9094

91-
// Sort languages case insensitive according to their name - needed for the user settings
95+
// Sort languages case-insensitive according to their name - needed for the user settings
9296
sort.Slice(allLangs, func(i, j int) bool {
9397
return strings.ToLower(allLangs[i].Name) < strings.ToLower(allLangs[j].Name)
9498
})
@@ -102,13 +106,18 @@ func Match(tags ...language.Tag) language.Tag {
102106

103107
// locale represents the information of localization.
104108
type locale struct {
105-
Lang string
109+
Lang, LangName string // these fields are used directly in templates: .i18n.Lang
106110
}
107111

108112
// NewLocale return a locale
109113
func NewLocale(lang string) Locale {
114+
langName := "unknown"
115+
if l, ok := allLangMap[lang]; ok {
116+
langName = l.Name
117+
}
110118
return &locale{
111-
Lang: lang,
119+
Lang: lang,
120+
LangName: langName,
112121
}
113122
}
114123

@@ -118,7 +127,16 @@ func (l *locale) Language() string {
118127

119128
// Tr translates content to target language.
120129
func (l *locale) Tr(format string, args ...interface{}) string {
121-
return i18n.Tr(l.Lang, format, args...)
130+
if setting.IsProd {
131+
return i18n.Tr(l.Lang, format, args...)
132+
}
133+
134+
// in development, we should show an error if a translation key is missing
135+
s, ok := TryTr(l.Lang, format, args...)
136+
if !ok {
137+
log.Error("missing i18n translation key: %q", format)
138+
}
139+
return s
122140
}
123141

124142
// Language specific rules for translating plural texts

routers/install/install.go

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,25 +71,16 @@ func Init(next http.Handler) http.Handler {
7171
Render: rnd,
7272
Session: session.GetSession(req),
7373
Data: map[string]interface{}{
74+
"i18n": locale,
7475
"Title": locale.Tr("install.install"),
7576
"PageIsInstall": true,
7677
"DbTypeNames": getDbTypeNames(),
77-
"i18n": locale,
78-
"Language": locale.Language(),
79-
"Lang": locale.Language(),
8078
"AllLangs": translation.AllLangs(),
81-
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
8279
"PageStartTime": startTime,
8380

8481
"PasswordHashAlgorithms": user_model.AvailableHashAlgorithms,
8582
},
8683
}
87-
for _, lang := range translation.AllLangs() {
88-
if lang.Lang == locale.Language() {
89-
ctx.Data["LangName"] = lang.Name
90-
break
91-
}
92-
}
9384
ctx.Req = context.WithContext(req, &ctx)
9485
next.ServeHTTP(resp, ctx.Req)
9586
})

routers/web/repo/blame.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m
255255
commitCnt++
256256

257257
// User avatar image
258-
commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Data["Lang"].(string))
258+
commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Locale.Language())
259259

260260
var avatar string
261261
if commit.User != nil {

routers/web/repo/issue_content_history.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func GetContentHistoryOverview(ctx *context.Context) {
2929
return
3030
}
3131

32-
lang := ctx.Data["Lang"].(string)
32+
lang := ctx.Locale.Language()
3333
editedHistoryCountMap, _ := issuesModel.QueryIssueContentHistoryEditedCountMap(db.DefaultContext, issue.ID)
3434
ctx.JSON(http.StatusOK, map[string]interface{}{
3535
"i18n": map[string]interface{}{
@@ -55,17 +55,17 @@ func GetContentHistoryList(ctx *context.Context) {
5555
// render history list to HTML for frontend dropdown items: (name, value)
5656
// name is HTML of "avatar + userName + userAction + timeSince"
5757
// value is historyId
58-
lang := ctx.Data["Lang"].(string)
58+
lang := ctx.Locale.Language()
5959
var results []map[string]interface{}
6060
for _, item := range items {
6161
var actionText string
6262
if item.IsDeleted {
63-
actionTextDeleted := i18n.Tr(lang, "repo.issues.content_history.deleted")
63+
actionTextDeleted := ctx.Locale.Tr("repo.issues.content_history.deleted")
6464
actionText = "<i data-history-is-deleted='1'>" + actionTextDeleted + "</i>"
6565
} else if item.IsFirstCreated {
66-
actionText = i18n.Tr(lang, "repo.issues.content_history.created")
66+
actionText = ctx.Locale.Tr("repo.issues.content_history.created")
6767
} else {
68-
actionText = i18n.Tr(lang, "repo.issues.content_history.edited")
68+
actionText = ctx.Locale.Tr("repo.issues.content_history.edited")
6969
}
7070
timeSinceText := timeutil.TimeSinceUnix(item.EditedUnix, lang)
7171
results = append(results, map[string]interface{}{

templates/admin/process-row.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<div class="df ac">
33
<div class="content f1">
44
<div class="header">{{.Process.Description}}</div>
5-
<div class="description"><span title="{{DateFmtLong .Process.Start}}">{{TimeSince .Process.Start .root.Lang}}</span></div>
5+
<div class="description"><span title="{{DateFmtLong .Process.Start}}">{{TimeSince .Process.Start .root.i18n.Lang}}</span></div>
66
</div>
77
<div>
88
<a class="delete-button icon" href="" data-url="{{.root.Link}}/cancel/{{.Process.PID}}" data-id="{{.Process.PID}}" data-name="{{.Process.Description}}">{{svg "octicon-trash" 16 "text-red"}}</a>

templates/base/footer_content.tmpl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
{{end}}
1010
<div class="ui language bottom floating slide up dropdown link item">
1111
{{svg "octicon-globe"}}
12-
<div class="text">{{.LangName}}</div>
12+
<div class="text">{{.i18n.LangName}}</div>
1313
<div class="menu language-menu">
1414
{{range .AllLangs}}
15-
<a lang="{{.Lang}}" data-url="{{AppSubUrl}}/?lang={{.Lang}}" class="item {{if eq $.Lang .Lang}}active selected{{end}}">{{.Name}}</a>
15+
<a lang="{{.Lang}}" data-url="{{AppSubUrl}}/?lang={{.Lang}}" class="item {{if eq $.i18n.Lang .Lang}}active selected{{end}}">{{.Name}}</a>
1616
{{end}}
1717
</div>
1818
</div>

templates/base/head.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<!DOCTYPE html>
2-
<html lang="{{.Lang}}" class="theme-{{.SignedUser.Theme}}">
2+
<html lang="{{.i18n.Lang}}" class="theme-{{.SignedUser.Theme}}">
33
<head>
44
<meta charset="utf-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1">

templates/repo/activity.tmpl

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@
131131
{{if not .IsTag}}
132132
<a class="title" href="{{$.RepoLink}}/src/{{.TagName | PathEscapeSegments}}">{{.Title | RenderEmoji}}</a>
133133
{{end}}
134-
{{TimeSinceUnix .CreatedUnix $.Lang}}
134+
{{TimeSinceUnix .CreatedUnix $.i18n.Lang}}
135135
</p>
136136
{{end}}
137137
</div>
@@ -150,7 +150,7 @@
150150
<p class="desc">
151151
<span class="ui purple label">{{$.i18n.Tr "repo.activity.merged_prs_label"}}</span>
152152
#{{.Index}} <a class="title" href="{{$.RepoLink}}/pulls/{{.Index}}">{{.Issue.Title | RenderEmoji}}</a>
153-
{{TimeSinceUnix .MergedUnix $.Lang}}
153+
{{TimeSinceUnix .MergedUnix $.i18n.Lang}}
154154
</p>
155155
{{end}}
156156
</div>
@@ -169,7 +169,7 @@
169169
<p class="desc">
170170
<span class="ui green label">{{$.i18n.Tr "repo.activity.opened_prs_label"}}</span>
171171
#{{.Index}} <a class="title" href="{{$.RepoLink}}/pulls/{{.Index}}">{{.Issue.Title | RenderEmoji}}</a>
172-
{{TimeSinceUnix .Issue.CreatedUnix $.Lang}}
172+
{{TimeSinceUnix .Issue.CreatedUnix $.i18n.Lang}}
173173
</p>
174174
{{end}}
175175
</div>
@@ -188,7 +188,7 @@
188188
<p class="desc">
189189
<span class="ui red label">{{$.i18n.Tr "repo.activity.closed_issue_label"}}</span>
190190
#{{.Index}} <a class="title" href="{{$.RepoLink}}/issues/{{.Index}}">{{.Title | RenderEmoji}}</a>
191-
{{TimeSinceUnix .ClosedUnix $.Lang}}
191+
{{TimeSinceUnix .ClosedUnix $.i18n.Lang}}
192192
</p>
193193
{{end}}
194194
</div>
@@ -207,7 +207,7 @@
207207
<p class="desc">
208208
<span class="ui green label">{{$.i18n.Tr "repo.activity.new_issue_label"}}</span>
209209
#{{.Index}} <a class="title" href="{{$.RepoLink}}/issues/{{.Index}}">{{.Title | RenderEmoji}}</a>
210-
{{TimeSinceUnix .CreatedUnix $.Lang}}
210+
{{TimeSinceUnix .CreatedUnix $.i18n.Lang}}
211211
</p>
212212
{{end}}
213213
</div>
@@ -231,7 +231,7 @@
231231
{{else}}
232232
<a class="title" href="{{$.RepoLink}}/issues/{{.Index}}">{{.Title | RenderEmoji}}</a>
233233
{{end}}
234-
{{TimeSinceUnix .UpdatedUnix $.Lang}}
234+
{{TimeSinceUnix .UpdatedUnix $.i18n.Lang}}
235235
</p>
236236
{{end}}
237237
</div>

templates/repo/commit_page.tmpl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
{{avatarByEmail .Commit.Author.Email .Commit.Author.Email 28 "mr-3"}}
4848
<strong>{{.Commit.Author.Name}}</strong>
4949
{{end}}
50-
<span class="text grey ml-3" id="authored-time">{{TimeSince .Commit.Author.When $.Lang}}</span>
50+
<span class="text grey ml-3" id="authored-time">{{TimeSince .Commit.Author.When $.i18n.Lang}}</span>
5151
{{if or (ne .Commit.Committer.Name .Commit.Author.Name) (ne .Commit.Committer.Email .Commit.Author.Email)}}
5252
<span class="text grey mx-3">{{.i18n.Tr "repo.diff.committed_by"}}</span>
5353
{{if ne .Verification.CommittingUser.ID 0}}
@@ -169,7 +169,7 @@
169169
{{else}}
170170
<strong>{{.NoteCommit.Author.Name}}</strong>
171171
{{end}}
172-
<span class="text grey" id="note-authored-time">{{TimeSince .NoteCommit.Author.When $.Lang}}</span>
172+
<span class="text grey" id="note-authored-time">{{TimeSince .NoteCommit.Author.When $.i18n.Lang}}</span>
173173
</div>
174174
<div class="ui bottom attached info segment git-notes">
175175
<pre class="commit-body">{{RenderNote $.Context .Note $.RepoLink $.Repository.ComposeMetas}}</pre>

0 commit comments

Comments
 (0)