Skip to content

Commit a60e8be

Browse files
authored
Refactor i18n, use Locale to provide i18n/translation related functions (#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 7b25a01 commit a60e8be

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>

templates/repo/commits_list.tmpl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,9 @@
7676
{{end}}
7777
</td>
7878
{{if .Committer}}
79-
<td class="text right aligned">{{TimeSince .Committer.When $.Lang}}</td>
79+
<td class="text right aligned">{{TimeSince .Committer.When $.i18n.Lang}}</td>
8080
{{else}}
81-
<td class="text right aligned">{{TimeSince .Author.When $.Lang}}</td>
81+
<td class="text right aligned">{{TimeSince .Author.When $.i18n.Lang}}</td>
8282
{{end}}
8383
</tr>
8484
{{end}}

templates/repo/diff/comments.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{{range .comments}}
22

3-
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.Lang }}
3+
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.root.i18n.Lang }}
44
<div class="comment" id="{{.HashTag}}">
55
{{if .OriginalAuthor }}
66
<span class="avatar"><img src="{{AppSubUrl}}/assets/img/avatar_default.png"></span>

templates/repo/issue/milestone_issues.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
</div>
2323
<div class="ui one column stackable grid">
2424
<div class="column">
25-
{{ $closedDate:= TimeSinceUnix .Milestone.ClosedDateUnix $.Lang }}
25+
{{ $closedDate:= TimeSinceUnix .Milestone.ClosedDateUnix $.i18n.Lang }}
2626
{{if .IsClosed}}
2727
{{svg "octicon-clock"}} {{$.i18n.Tr "repo.milestones.closed" $closedDate|Str2html}}
2828
{{else}}

templates/repo/issue/milestones.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
</div>
6969
</div>
7070
<div class="meta">
71-
{{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.Lang }}
71+
{{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.i18n.Lang }}
7272
{{if .IsClosed}}
7373
{{svg "octicon-clock"}} {{$.i18n.Tr "repo.milestones.closed" $closedDate|Str2html}}
7474
{{else}}

templates/repo/issue/view_content.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
<input type="hidden" id="issueIndex" value="{{.Issue.Index}}"/>
1616
<input type="hidden" id="type" value="{{.IssueType}}">
1717

18-
{{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.Lang }}
18+
{{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.i18n.Lang }}
1919
<div class="twelve wide column comment-list prevent-before-timeline">
2020
<ui class="ui timeline">
2121
<div id="{{.Issue.HashTag}}" class="timeline-item comment first">

templates/repo/issue/view_content/comments.tmpl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{{ template "base/alert" }}
22
{{range .Issue.Comments}}
33
{{if call $.ShouldShowCommentType .Type}}
4-
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.Lang }}
4+
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.i18n.Lang }}
55

66
<!-- 0 = COMMENT, 1 = REOPEN, 2 = CLOSE, 3 = ISSUE_REF, 4 = COMMIT_REF,
77
5 = COMMENT_REF, 6 = PULL_REF, 7 = COMMENT_LABEL, 12 = START_TRACKING,
@@ -146,7 +146,7 @@
146146
{{else if eq .RefAction 2 }}
147147
{{ $refTr = "repo.issues.ref_reopening_from" }}
148148
{{end}}
149-
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.Lang }}
149+
{{ $createdStr:= TimeSinceUnix .CreatedUnix $.i18n.Lang }}
150150
<div class="timeline-item event" id="{{.HashTag}}">
151151
<span class="badge">{{svg "octicon-bookmark"}}</span>
152152
<a href="{{.Poster.HomeLink}}">
@@ -557,7 +557,7 @@
557557
<div id="code-comments-{{(index $comms 0).ID}}" class="comment-code-cloud ui segment{{if $resolved}} hide{{end}}">
558558
<div class="ui comments mb-0">
559559
{{range $comms}}
560-
{{ $createdSubStr:= TimeSinceUnix .CreatedUnix $.Lang }}
560+
{{ $createdSubStr:= TimeSinceUnix .CreatedUnix $.i18n.Lang }}
561561
<div class="comment code-comment pb-4" id="{{.HashTag}}">
562562
<div class="content">
563563
<div class="header comment-header">

templates/repo/issue/view_content/pull.tmpl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<div class="ui segment">
55
<h4>{{$.i18n.Tr "repo.issues.review.reviewers"}}</h4>
66
{{range .PullReviewers}}
7-
{{ $createdStr:= TimeSinceUnix .Review.UpdatedUnix $.Lang }}
7+
{{ $createdStr:= TimeSinceUnix .Review.UpdatedUnix $.i18n.Lang }}
88
<div class="ui divider"></div>
99
<div class="review-item">
1010
<div class="review-item-left">
@@ -82,7 +82,7 @@
8282
</div>
8383
{{end}}
8484
{{range .OriginalReviews}}
85-
{{ $createdStr:= TimeSinceUnix .UpdatedUnix $.Lang }}
85+
{{ $createdStr:= TimeSinceUnix .UpdatedUnix $.i18n.Lang }}
8686
<div class="ui divider"></div>
8787
<div class="review-item">
8888
<div class="review-item-left">

templates/repo/issue/view_title.tmpl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
{{$baseHref = printf "<a href=\"%s\">%s</a>" (.BaseBranchHTMLURL | Escape) $baseHref}}
4141
{{end}}
4242
{{if .Issue.PullRequest.HasMerged}}
43-
{{ $mergedStr:= TimeSinceUnix .Issue.PullRequest.MergedUnix $.Lang }}
43+
{{ $mergedStr:= TimeSinceUnix .Issue.PullRequest.MergedUnix $.i18n.Lang }}
4444
{{if .Issue.OriginalAuthor }}
4545
{{.Issue.OriginalAuthor}}
4646
<span class="pull-desc">{{$.i18n.Tr "repo.pulls.merged_title_desc" .NumCommits $headHref $baseHref $mergedStr | Safe}}</span>
@@ -88,7 +88,7 @@
8888
</span>
8989
{{end}}
9090
{{else}}
91-
{{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.Lang }}
91+
{{ $createdStr:= TimeSinceUnix .Issue.CreatedUnix $.i18n.Lang }}
9292
<span class="time-desc">
9393
{{if .Issue.OriginalAuthor }}
9494
{{$.i18n.Tr "repo.issues.opened_by_fake" $createdStr (.Issue.OriginalAuthor|Escape) | Safe}}

templates/repo/projects/list.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
<li class="item">
4343
{{svg "octicon-project"}} <a href="{{$.RepoLink}}/projects/{{.ID}}">{{.Title}}</a>
4444
<div class="meta">
45-
{{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.Lang }}
45+
{{ $closedDate:= TimeSinceUnix .ClosedDateUnix $.i18n.Lang }}
4646
{{if .IsClosed }}
4747
{{svg "octicon-clock"}} {{$.i18n.Tr "repo.milestones.closed" $closedDate|Str2html}}
4848
{{end}}

0 commit comments

Comments
 (0)