From 4a469c8e1b3c1d153316aec9fd8cbdd3e1dd54e8 Mon Sep 17 00:00:00 2001
From: wxiaoguang
Date: Tue, 5 Nov 2024 14:04:26 +0800
Subject: [PATCH] Refactor template ctx and render utils (#32422)
Clean up the templates
---
modules/templates/helper.go | 41 +++++++------
modules/templates/util_date.go | 18 ------
modules/templates/util_date_legacy.go | 23 +++++++
modules/templates/util_render.go | 61 +++++++++++--------
modules/templates/util_render_legacy.go | 52 ++++++++++++++++
modules/templates/util_render_test.go | 33 +++++-----
routers/web/feed/convert.go | 3 +-
routers/web/org/projects.go | 6 +-
routers/web/repo/issue.go | 2 +-
services/context/context.go | 5 +-
templates/base/head_script.tmpl | 4 +-
templates/explore/repo_list.tmpl | 2 +-
templates/org/team/new.tmpl | 8 +--
templates/org/team/sidebar.tmpl | 6 +-
templates/package/content/cargo.tmpl | 2 +-
templates/package/content/chef.tmpl | 2 +-
templates/package/content/composer.tmpl | 2 +-
templates/package/content/npm.tmpl | 2 +-
templates/package/content/nuget.tmpl | 6 +-
templates/package/content/pub.tmpl | 2 +-
templates/package/content/pypi.tmpl | 4 +-
templates/projects/view.tmpl | 2 +-
templates/repo/branch/list.tmpl | 4 +-
templates/repo/commit_page.tmpl | 4 +-
templates/repo/commits_list.tmpl | 6 +-
templates/repo/commits_list_small.tmpl | 4 +-
templates/repo/diff/compare.tmpl | 2 +-
templates/repo/graph/commits.tmpl | 4 +-
templates/repo/header.tmpl | 4 +-
templates/repo/issue/card.tmpl | 4 +-
templates/repo/issue/fields/checkboxes.tmpl | 2 +-
templates/repo/issue/fields/header.tmpl | 2 +-
templates/repo/issue/fields/markdown.tmpl | 2 +-
templates/repo/issue/filter_actions.tmpl | 2 +-
templates/repo/issue/filter_list.tmpl | 2 +-
templates/repo/issue/labels/label.tmpl | 2 +-
templates/repo/issue/labels/label_list.tmpl | 8 +--
.../issue/labels/labels_selector_field.tmpl | 8 +--
templates/repo/issue/new_form.tmpl | 10 +--
.../repo/issue/view_content/comments.tmpl | 10 +--
templates/repo/issue/view_content/pull.tmpl | 2 +-
.../repo/issue/view_content/sidebar.tmpl | 16 ++---
templates/repo/issue/view_title.tmpl | 2 +-
templates/repo/latest_commit.tmpl | 4 +-
templates/repo/pulse.tmpl | 14 ++---
templates/repo/settings/collaboration.tmpl | 2 +-
templates/repo/settings/lfs_file_find.tmpl | 2 +-
templates/repo/settings/navbar.tmpl | 2 +-
templates/repo/settings/options.tmpl | 50 +++++++--------
templates/repo/view_list.tmpl | 2 +-
templates/shared/issuelist.tmpl | 4 +-
templates/user/dashboard/feeds.tmpl | 18 +++---
.../user/notification/notification_div.tmpl | 2 +-
53 files changed, 281 insertions(+), 205 deletions(-)
create mode 100644 modules/templates/util_date_legacy.go
create mode 100644 modules/templates/util_render_legacy.go
diff --git a/modules/templates/helper.go b/modules/templates/helper.go
index a01aad06a173e..efaa10624bd87 100644
--- a/modules/templates/helper.go
+++ b/modules/templates/helper.go
@@ -73,11 +73,6 @@ func NewFuncMap() template.FuncMap {
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
},
- // for backward compatibility only, do not use them anymore
- "TimeSince": timeSinceLegacy,
- "TimeSinceUnix": timeSinceLegacy,
- "DateTime": dateTimeLegacy,
-
// -----------------------------------------------------------------
// setting
"AppName": func() string {
@@ -156,18 +151,8 @@ func NewFuncMap() template.FuncMap {
// -----------------------------------------------------------------
// render
- "RenderCommitMessage": RenderCommitMessage,
- "RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject,
-
- "RenderCommitBody": renderCommitBody,
- "RenderCodeBlock": renderCodeBlock,
- "RenderIssueTitle": renderIssueTitle,
- "RenderEmoji": renderEmoji,
- "ReactionToEmoji": reactionToEmoji,
-
- "RenderMarkdownToHtml": RenderMarkdownToHtml,
- "RenderLabel": renderLabel,
- "RenderLabels": RenderLabels,
+ "RenderCodeBlock": renderCodeBlock,
+ "ReactionToEmoji": reactionToEmoji,
// -----------------------------------------------------------------
// misc
@@ -179,6 +164,22 @@ func NewFuncMap() template.FuncMap {
"FilenameIsImage": filenameIsImage,
"TabSizeClass": tabSizeClass,
+
+ // for backward compatibility only, do not use them anymore
+ "TimeSince": timeSinceLegacy,
+ "TimeSinceUnix": timeSinceLegacy,
+ "DateTime": dateTimeLegacy,
+
+ "RenderEmoji": renderEmojiLegacy,
+ "RenderLabel": renderLabelLegacy,
+ "RenderLabels": renderLabelsLegacy,
+ "RenderIssueTitle": renderIssueTitleLegacy,
+
+ "RenderMarkdownToHtml": renderMarkdownToHtmlLegacy,
+
+ "RenderCommitMessage": renderCommitMessageLegacy,
+ "RenderCommitMessageLinkSubject": renderCommitMessageLinkSubjectLegacy,
+ "RenderCommitBody": renderCommitBodyLegacy,
}
}
@@ -296,3 +297,9 @@ func userThemeName(user *user_model.User) string {
}
return setting.UI.DefaultTheme
}
+
+func panicIfDevOrTesting() {
+ if !setting.IsProd || setting.IsInTesting {
+ panic("legacy template functions are for backward compatibility only, do not use them in new code")
+ }
+}
diff --git a/modules/templates/util_date.go b/modules/templates/util_date.go
index b9e04401f15f5..4a794e6f30c7b 100644
--- a/modules/templates/util_date.go
+++ b/modules/templates/util_date.go
@@ -12,7 +12,6 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
- "code.gitea.io/gitea/modules/translation"
)
type DateUtils struct{}
@@ -54,23 +53,6 @@ func parseLegacy(datetime string) time.Time {
return t
}
-func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML {
- if !setting.IsProd || setting.IsInTesting {
- panic("dateTimeLegacy is for backward compatibility only, do not use it in new code")
- }
- if s, ok := datetime.(string); ok {
- datetime = parseLegacy(s)
- }
- return dateTimeFormat(format, datetime)
-}
-
-func timeSinceLegacy(time any, _ translation.Locale) template.HTML {
- if !setting.IsProd || setting.IsInTesting {
- panic("timeSinceLegacy is for backward compatibility only, do not use it in new code")
- }
- return TimeSince(time)
-}
-
func anyToTime(any any) (t time.Time, isZero bool) {
switch v := any.(type) {
case nil:
diff --git a/modules/templates/util_date_legacy.go b/modules/templates/util_date_legacy.go
new file mode 100644
index 0000000000000..ceefb0044717a
--- /dev/null
+++ b/modules/templates/util_date_legacy.go
@@ -0,0 +1,23 @@
+// Copyright 2024 The Gitea Authors. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+package templates
+
+import (
+ "html/template"
+
+ "code.gitea.io/gitea/modules/translation"
+)
+
+func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML {
+ panicIfDevOrTesting()
+ if s, ok := datetime.(string); ok {
+ datetime = parseLegacy(s)
+ }
+ return dateTimeFormat(format, datetime)
+}
+
+func timeSinceLegacy(time any, _ translation.Locale) template.HTML {
+ panicIfDevOrTesting()
+ return TimeSince(time)
+}
diff --git a/modules/templates/util_render.go b/modules/templates/util_render.go
index 6eee007f34683..1201828345715 100644
--- a/modules/templates/util_render.go
+++ b/modules/templates/util_render.go
@@ -24,13 +24,21 @@ import (
"code.gitea.io/gitea/modules/util"
)
+type RenderUtils struct {
+ ctx context.Context
+}
+
+func NewRenderUtils(ctx context.Context) *RenderUtils {
+ return &RenderUtils{ctx: ctx}
+}
+
// RenderCommitMessage renders commit message with XSS-safe and special links.
-func RenderCommitMessage(ctx context.Context, msg string, metas map[string]string) template.HTML {
+func (ut *RenderUtils) RenderCommitMessage(msg string, metas map[string]string) template.HTML {
cleanMsg := template.HTMLEscapeString(msg)
// we can safely assume that it will not return any error, since there
// shouldn't be any special HTML.
fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
- Ctx: ctx,
+ Ctx: ut.ctx,
Metas: metas,
}, cleanMsg)
if err != nil {
@@ -44,9 +52,9 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin
return renderCodeBlock(template.HTML(msgLines[0]))
}
-// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to
+// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// the provided default url, handling for special links without email to links.
-func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
+func (ut *RenderUtils) RenderCommitMessageLinkSubject(msg, urlDefault string, metas map[string]string) template.HTML {
msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
@@ -60,7 +68,7 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
// we can safely assume that it will not return any error, since there
// shouldn't be any special HTML.
renderedMessage, err := markup.RenderCommitMessageSubject(&markup.RenderContext{
- Ctx: ctx,
+ Ctx: ut.ctx,
DefaultLink: urlDefault,
Metas: metas,
}, template.HTMLEscapeString(msgLine))
@@ -71,8 +79,8 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
return renderCodeBlock(template.HTML(renderedMessage))
}
-// renderCommitBody extracts the body of a commit message without its title.
-func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
+// RenderCommitBody extracts the body of a commit message without its title.
+func (ut *RenderUtils) RenderCommitBody(msg string, metas map[string]string) template.HTML {
msgLine := strings.TrimSpace(msg)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
@@ -86,7 +94,7 @@ func renderCommitBody(ctx context.Context, msg string, metas map[string]string)
}
renderedMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
- Ctx: ctx,
+ Ctx: ut.ctx,
Metas: metas,
}, template.HTMLEscapeString(msgLine))
if err != nil {
@@ -105,22 +113,22 @@ func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
return template.HTML(htmlWithCodeTags)
}
-// renderIssueTitle renders issue/pull title with defined post processors
-func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
+// RenderIssueTitle renders issue/pull title with defined post processors
+func (ut *RenderUtils) RenderIssueTitle(text string, metas map[string]string) template.HTML {
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
- Ctx: ctx,
+ Ctx: ut.ctx,
Metas: metas,
}, template.HTMLEscapeString(text))
if err != nil {
log.Error("RenderIssueTitle: %v", err)
- return template.HTML("")
+ return ""
}
return template.HTML(renderedText)
}
-// renderLabel renders a label
-// locale is needed due to an import cycle with our context providing the `Tr` function
-func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
+// RenderLabel renders a label
+func (ut *RenderUtils) RenderLabel(label *issues_model.Label) template.HTML {
+ locale := ut.ctx.Value(translation.ContextKey).(translation.Locale)
var extraCSSClasses string
textColor := util.ContrastColor(label.Color)
labelScope := label.ExclusiveScope()
@@ -134,12 +142,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m
if labelScope == "" {
// Regular label
return HTMLFormat(`%s
`,
- extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name))
+ extraCSSClasses, textColor, label.Color, descriptionText, ut.RenderEmoji(label.Name))
}
// Scoped label
- scopeHTML := renderEmoji(ctx, labelScope)
- itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])
+ scopeHTML := ut.RenderEmoji(labelScope)
+ itemHTML := ut.RenderEmoji(label.Name[len(labelScope)+1:])
// Make scope and item background colors slightly darker and lighter respectively.
// More contrast needed with higher luminance, empirically tweaked.
@@ -176,13 +184,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m
textColor, itemColor, itemHTML)
}
-// renderEmoji renders html text with emoji post processors
-func renderEmoji(ctx context.Context, text string) template.HTML {
- renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
- template.HTMLEscapeString(text))
+// RenderEmoji renders html text with emoji post processors
+func (ut *RenderUtils) RenderEmoji(text string) template.HTML {
+ renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ut.ctx}, template.HTMLEscapeString(text))
if err != nil {
log.Error("RenderEmoji: %v", err)
- return template.HTML("")
+ return ""
}
return template.HTML(renderedText)
}
@@ -200,9 +207,9 @@ func reactionToEmoji(reaction string) template.HTML {
return template.HTML(fmt.Sprintf(` `, reaction, setting.StaticURLPrefix, url.PathEscape(reaction)))
}
-func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //nolint:revive
+func (ut *RenderUtils) MarkdownToHtml(input string) template.HTML { //nolint:revive
output, err := markdown.RenderString(&markup.RenderContext{
- Ctx: ctx,
+ Ctx: ut.ctx,
Metas: map[string]string{"mode": "document"},
}, input)
if err != nil {
@@ -211,7 +218,7 @@ func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //n
return output
}
-func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
+func (ut *RenderUtils) RenderLabels(labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
isPullRequest := issue != nil && issue.IsPull
baseLink := fmt.Sprintf("%s/%s", repoLink, util.Iif(isPullRequest, "pulls", "issues"))
htmlCode := ``
@@ -220,7 +227,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
if label == nil {
continue
}
- htmlCode += fmt.Sprintf(`%s `, baseLink, label.ID, renderLabel(ctx, locale, label))
+ htmlCode += fmt.Sprintf(`%s `, baseLink, label.ID, ut.RenderLabel(label))
}
htmlCode += " "
return template.HTML(htmlCode)
diff --git a/modules/templates/util_render_legacy.go b/modules/templates/util_render_legacy.go
new file mode 100644
index 0000000000000..994f2fa064cb5
--- /dev/null
+++ b/modules/templates/util_render_legacy.go
@@ -0,0 +1,52 @@
+// Copyright 2024 The Gitea Authors. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+package templates
+
+import (
+ "context"
+ "html/template"
+
+ issues_model "code.gitea.io/gitea/models/issues"
+ "code.gitea.io/gitea/modules/translation"
+)
+
+func renderEmojiLegacy(ctx context.Context, text string) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderEmoji(text)
+}
+
+func renderLabelLegacy(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderLabel(label)
+}
+
+func renderLabelsLegacy(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderLabels(labels, repoLink, issue)
+}
+
+func renderMarkdownToHtmlLegacy(ctx context.Context, input string) template.HTML { //nolint:revive
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).MarkdownToHtml(input)
+}
+
+func renderCommitMessageLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderCommitMessage(msg, metas)
+}
+
+func renderCommitMessageLinkSubjectLegacy(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderCommitMessageLinkSubject(msg, urlDefault, metas)
+}
+
+func renderIssueTitleLegacy(ctx context.Context, text string, metas map[string]string) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderIssueTitle(text, metas)
+}
+
+func renderCommitBodyLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML {
+ panicIfDevOrTesting()
+ return NewRenderUtils(ctx).RenderCommitBody(msg, metas)
+}
diff --git a/modules/templates/util_render_test.go b/modules/templates/util_render_test.go
index ba47c34efc193..3e4ea04c63191 100644
--- a/modules/templates/util_render_test.go
+++ b/modules/templates/util_render_test.go
@@ -65,9 +65,14 @@ func TestMain(m *testing.M) {
os.Exit(m.Run())
}
+func newTestRenderUtils() *RenderUtils {
+ ctx := context.Background()
+ ctx = context.WithValue(ctx, translation.ContextKey, &translation.MockLocale{})
+ return NewRenderUtils(ctx)
+}
+
func TestRenderCommitBody(t *testing.T) {
type args struct {
- ctx context.Context
msg string
metas map[string]string
}
@@ -79,7 +84,6 @@ func TestRenderCommitBody(t *testing.T) {
{
name: "multiple lines",
args: args{
- ctx: context.Background(),
msg: "first line\nsecond line",
},
want: "second line",
@@ -87,7 +91,6 @@ func TestRenderCommitBody(t *testing.T) {
{
name: "multiple lines with leading newlines",
args: args{
- ctx: context.Background(),
msg: "\n\n\n\nfirst line\nsecond line",
},
want: "second line",
@@ -95,15 +98,15 @@ func TestRenderCommitBody(t *testing.T) {
{
name: "multiple lines with trailing newlines",
args: args{
- ctx: context.Background(),
msg: "first line\nsecond line\n\n\n",
},
want: "second line",
},
}
+ ut := newTestRenderUtils()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- assert.Equalf(t, tt.want, renderCommitBody(tt.args.ctx, tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v, %v)", tt.args.ctx, tt.args.msg, tt.args.metas)
+ assert.Equalf(t, tt.want, ut.RenderCommitBody(tt.args.msg, tt.args.metas), "RenderCommitBody(%v, %v)", tt.args.msg, tt.args.metas)
})
}
@@ -127,19 +130,19 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit
#123
space`
- assert.EqualValues(t, expected, renderCommitBody(context.Background(), testInput(), testMetas))
+ assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitBody(testInput(), testMetas))
}
func TestRenderCommitMessage(t *testing.T) {
expected := `space @mention-user `
- assert.EqualValues(t, expected, RenderCommitMessage(context.Background(), testInput(), testMetas))
+ assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitMessage(testInput(), testMetas))
}
func TestRenderCommitMessageLinkSubject(t *testing.T) {
expected := `space @mention-user `
- assert.EqualValues(t, expected, renderCommitMessageLinkSubject(context.Background(), testInput(), "https://example.com/link", testMetas))
+ assert.EqualValues(t, expected, newTestRenderUtils().RenderCommitMessageLinkSubject(testInput(), "https://example.com/link", testMetas))
}
func TestRenderIssueTitle(t *testing.T) {
@@ -165,7 +168,7 @@ mail@domain.com
space
`
expected = strings.ReplaceAll(expected, "", " ")
- assert.EqualValues(t, expected, renderIssueTitle(context.Background(), testInput(), testMetas))
+ assert.EqualValues(t, expected, newTestRenderUtils().RenderIssueTitle(testInput(), testMetas))
}
func TestRenderMarkdownToHtml(t *testing.T) {
@@ -190,25 +193,23 @@ com 88fc37a3c0a4dda553bdcfc80c178a58247f42fb mit
#123
space
`
- assert.Equal(t, expected, string(RenderMarkdownToHtml(context.Background(), testInput())))
+ assert.Equal(t, expected, string(newTestRenderUtils().MarkdownToHtml(testInput())))
}
func TestRenderLabels(t *testing.T) {
- ctx := context.Background()
- locale := &translation.MockLocale{}
-
+ ut := newTestRenderUtils()
label := &issues.Label{ID: 123, Name: "label-name", Color: "label-color"}
issue := &issues.Issue{}
expected := `/owner/repo/issues?labels=123`
- assert.Contains(t, RenderLabels(ctx, locale, []*issues.Label{label}, "/owner/repo", issue), expected)
+ assert.Contains(t, ut.RenderLabels([]*issues.Label{label}, "/owner/repo", issue), expected)
label = &issues.Label{ID: 123, Name: "label-name", Color: "label-color"}
issue = &issues.Issue{IsPull: true}
expected = `/owner/repo/pulls?labels=123`
- assert.Contains(t, RenderLabels(ctx, locale, []*issues.Label{label}, "/owner/repo", issue), expected)
+ assert.Contains(t, ut.RenderLabels([]*issues.Label{label}, "/owner/repo", issue), expected)
}
func TestUserMention(t *testing.T) {
- rendered := RenderMarkdownToHtml(context.Background(), "@no-such-user @mention-user @mention-user")
+ rendered := newTestRenderUtils().MarkdownToHtml("@no-such-user @mention-user @mention-user")
assert.EqualValues(t, `@no-such-user @mention-user @mention-user
`, strings.TrimSpace(string(rendered)))
}
diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go
index 774644e29ae21..3f33e9933a2ea 100644
--- a/routers/web/feed/convert.go
+++ b/routers/web/feed/convert.go
@@ -71,6 +71,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content
// feedActionsToFeedItems convert gitea's Action feed to feeds Item
func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) {
+ renderUtils := templates.NewRenderUtils(ctx)
for _, act := range actions {
act.LoadActUser(ctx)
@@ -215,7 +216,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions activities_model.Actio
desc += fmt.Sprintf("%s \n%s",
html.EscapeString(fmt.Sprintf("%s/commit/%s", act.GetRepoAbsoluteLink(ctx), commit.Sha1)),
commit.Sha1,
- templates.RenderCommitMessage(ctx, commit.Message, nil),
+ renderUtils.RenderCommitMessage(commit.Message, nil),
)
}
diff --git a/routers/web/org/projects.go b/routers/web/org/projects.go
index 2a5434b4147f6..6dfefbf68d243 100644
--- a/routers/web/org/projects.go
+++ b/routers/web/org/projects.go
@@ -103,9 +103,9 @@ func Projects(ctx *context.Context) {
} else {
ctx.Data["State"] = "open"
}
-
+ renderUtils := templates.NewRenderUtils(ctx)
for _, project := range projects {
- project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description)
+ project.RenderedContent = renderUtils.MarkdownToHtml(project.Description)
}
err = shared_user.LoadHeaderCount(ctx)
@@ -435,7 +435,7 @@ func ViewProject(ctx *context.Context) {
ctx.Data["SelectLabels"] = selectLabels
ctx.Data["AssigneeID"] = assigneeID
- project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description)
+ project.RenderedContent = templates.NewRenderUtils(ctx).MarkdownToHtml(project.Description)
ctx.Data["LinkedPRs"] = linkedPrsMap
ctx.Data["PageIsViewProjects"] = true
ctx.Data["CanWriteProjects"] = canWriteProjects(ctx)
diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go
index 507b5af9d904a..93e2b5e748662 100644
--- a/routers/web/repo/issue.go
+++ b/routers/web/repo/issue.go
@@ -2215,7 +2215,7 @@ func GetIssueInfo(ctx *context.Context) {
ctx.JSON(http.StatusOK, map[string]any{
"convertedIssue": convert.ToIssue(ctx, ctx.Doer, issue),
- "renderedLabels": templates.RenderLabels(ctx, ctx.Locale, issue.Labels, ctx.Repo.RepoLink, issue),
+ "renderedLabels": templates.NewRenderUtils(ctx).RenderLabels(issue.Labels, ctx.Repo.RepoLink, issue),
})
}
diff --git a/services/context/context.go b/services/context/context.go
index 42f7c3d9d1d8a..6c7128ef6866c 100644
--- a/services/context/context.go
+++ b/services/context/context.go
@@ -100,6 +100,7 @@ func NewTemplateContextForWeb(ctx *Context) TemplateContext {
tmplCtx := NewTemplateContext(ctx)
tmplCtx["Locale"] = ctx.Base.Locale
tmplCtx["AvatarUtils"] = templates.NewAvatarUtils(ctx)
+ tmplCtx["RenderUtils"] = templates.NewRenderUtils(ctx)
tmplCtx["RootData"] = ctx.Data
tmplCtx["Consts"] = map[string]any{
"RepoUnitTypeCode": unit.TypeCode,
@@ -154,7 +155,9 @@ func Contexter() func(next http.Handler) http.Handler {
ctx := NewWebContext(base, rnd, session.GetContextSession(req))
ctx.Data.MergeFrom(middleware.CommonTemplateContextData())
- ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this
+ if setting.IsProd && !setting.IsInTesting {
+ ctx.Data["Context"] = ctx // TODO: use "ctx" in template and remove this
+ }
ctx.Data["CurrentURL"] = setting.AppSubURL + req.URL.RequestURI()
ctx.Data["Link"] = ctx.Link
diff --git a/templates/base/head_script.tmpl b/templates/base/head_script.tmpl
index 22e08e9c8f69c..c0c7235e3b02e 100644
--- a/templates/base/head_script.tmpl
+++ b/templates/base/head_script.tmpl
@@ -21,10 +21,10 @@ If you introduce mistakes in it, Gitea JavaScript code wouldn't run correctly.
{{if or .Participants .Assignees .MentionableTeams}}
mentionValues: Array.from(new Map([
{{- range .Participants -}}
- ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}],
+ ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}],
{{- end -}}
{{- range .Assignees -}}
- ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}],
+ ['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}],
{{- end -}}
{{- range .MentionableTeams -}}
['{{$.MentionableTeamsOrg}}/{{.Name}}', {key: '{{$.MentionableTeamsOrg}}/{{.Name}}', value: '{{$.MentionableTeamsOrg}}/{{.Name}}', name: '{{$.MentionableTeamsOrg}}/{{.Name}}', avatar: '{{$.MentionableTeamsOrgAvatar}}'}],
diff --git a/templates/explore/repo_list.tmpl b/templates/explore/repo_list.tmpl
index 742e83834d06f..219b1255c0a12 100644
--- a/templates/explore/repo_list.tmpl
+++ b/templates/explore/repo_list.tmpl
@@ -49,7 +49,7 @@
- {{$description := .DescriptionHTML $.Context}}
+ {{$description := .DescriptionHTML ctx}}
{{if $description}}
{{$description}}
{{end}}
diff --git a/templates/org/team/new.tmpl b/templates/org/team/new.tmpl
index 9608eac154ef3..410a3c4b62fb7 100644
--- a/templates/org/team/new.tmpl
+++ b/templates/org/team/new.tmpl
@@ -99,17 +99,17 @@
-
+
-
+
-
+
@@ -121,7 +121,7 @@
{{if lt $unit.MaxPerm 2}}
{{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Readme}}
{{if .PackageDescriptor.Metadata.Description}}{{.PackageDescriptor.Metadata.Description}}
{{end}}
- {{if .PackageDescriptor.Metadata.Readme}}{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}}
+ {{if .PackageDescriptor.Metadata.Readme}}{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}}
{{end}}
{{if .PackageDescriptor.Metadata.Dependencies}}
diff --git a/templates/package/content/chef.tmpl b/templates/package/content/chef.tmpl
index 03ce9f852bde8..b3713808f659b 100644
--- a/templates/package/content/chef.tmpl
+++ b/templates/package/content/chef.tmpl
@@ -20,7 +20,7 @@
{{if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
{{end}}
- {{if .PackageDescriptor.Metadata.LongDescription}}{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.LongDescription}}{{end}}
+ {{if .PackageDescriptor.Metadata.LongDescription}}{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.LongDescription}}{{end}}
{{end}}
diff --git a/templates/package/content/composer.tmpl b/templates/package/content/composer.tmpl
index 8d48e6c95d5ee..45698208696ba 100644
--- a/templates/package/content/composer.tmpl
+++ b/templates/package/content/composer.tmpl
@@ -25,7 +25,7 @@
{{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Comments}}
{{if .PackageDescriptor.Metadata.Description}}{{.PackageDescriptor.Metadata.Description}}
{{end}}
- {{if .PackageDescriptor.Metadata.Readme}}{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}}
+ {{if .PackageDescriptor.Metadata.Readme}}{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}}
{{if .PackageDescriptor.Metadata.Comments}}{{StringUtils.Join .PackageDescriptor.Metadata.Comments " "}}
{{end}}
{{end}}
diff --git a/templates/package/content/npm.tmpl b/templates/package/content/npm.tmpl
index 01298a664c734..bb024348d07f3 100644
--- a/templates/package/content/npm.tmpl
+++ b/templates/package/content/npm.tmpl
@@ -25,7 +25,7 @@
{{if .PackageDescriptor.Metadata.Readme}}
- {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
+ {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{else if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
diff --git a/templates/package/content/nuget.tmpl b/templates/package/content/nuget.tmpl
index f1fe420c0ba24..5bb98a86ddf9e 100644
--- a/templates/package/content/nuget.tmpl
+++ b/templates/package/content/nuget.tmpl
@@ -18,9 +18,9 @@
{{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.ReleaseNotes .PackageDescriptor.Metadata.Readme}}
- {{if .PackageDescriptor.Metadata.Description}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Description}}
{{end}}
- {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}}
- {{if .PackageDescriptor.Metadata.ReleaseNotes}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.ReleaseNotes}}
{{end}}
+ {{if .PackageDescriptor.Metadata.Description}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Description}}
{{end}}
+ {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}}
+ {{if .PackageDescriptor.Metadata.ReleaseNotes}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.ReleaseNotes}}
{{end}}
{{end}}
{{if .PackageDescriptor.Metadata.Dependencies}}
diff --git a/templates/package/content/pub.tmpl b/templates/package/content/pub.tmpl
index f2c7ac938faad..2f63cde3a639c 100644
--- a/templates/package/content/pub.tmpl
+++ b/templates/package/content/pub.tmpl
@@ -14,6 +14,6 @@
{{if or .PackageDescriptor.Metadata.Description .PackageDescriptor.Metadata.Readme}}
{{if .PackageDescriptor.Metadata.Description}}
{{.PackageDescriptor.Metadata.Description}}
{{end}}
- {{if .PackageDescriptor.Metadata.Readme}}
{{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Readme}}
{{end}}
+ {{if .PackageDescriptor.Metadata.Readme}}
{{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Readme}}
{{end}}
{{end}}
{{end}}
diff --git a/templates/package/content/pypi.tmpl b/templates/package/content/pypi.tmpl
index 817fced97b960..2a22a6ed71ba6 100644
--- a/templates/package/content/pypi.tmpl
+++ b/templates/package/content/pypi.tmpl
@@ -16,9 +16,9 @@
{{if .PackageDescriptor.Metadata.Summary}}{{.PackageDescriptor.Metadata.Summary}}{{end}}
{{if .PackageDescriptor.Metadata.LongDescription}}
- {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.LongDescription}}
+ {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.LongDescription}}
{{else if .PackageDescriptor.Metadata.Description}}
- {{RenderMarkdownToHtml $.Context .PackageDescriptor.Metadata.Description}}
+ {{ctx.RenderUtils.MarkdownToHtml .PackageDescriptor.Metadata.Description}}
{{end}}
{{end}}
diff --git a/templates/projects/view.tmpl b/templates/projects/view.tmpl
index f5c1bb76703c4..71f9d059adb9b 100644
--- a/templates/projects/view.tmpl
+++ b/templates/projects/view.tmpl
@@ -49,7 +49,7 @@
{{svg "octicon-check"}}
{{end}}
{{end}}
- {{RenderLabel $.Context ctx.Locale .}}
+ {{ctx.RenderUtils.RenderLabel .}}
{{template "repo/issue/labels/label_archived" .}}
{{end}}
diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl
index 6e2a5570c712a..5484024ff8197 100644
--- a/templates/repo/branch/list.tmpl
+++ b/templates/repo/branch/list.tmpl
@@ -27,7 +27,7 @@
{{svg "octicon-copy" 14}}
{{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DefaultBranchBranch.DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DefaultBranchBranch.DBBranch.CommitID)}}
- {{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DefaultBranchBranch.DBBranch.CommitMessage (.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DefaultBranchBranch.DBBranch.CommitTime}}{{if .DefaultBranchBranch.DBBranch.Pusher}} {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}
+ {{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DefaultBranchBranch.DBBranch.CommitID}} · {{ctx.RenderUtils.RenderCommitMessage .DefaultBranchBranch.DBBranch.CommitMessage (.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DefaultBranchBranch.DBBranch.CommitTime}}{{if .DefaultBranchBranch.DBBranch.Pusher}} {{template "shared/user/avatarlink" dict "user" .DefaultBranchBranch.DBBranch.Pusher}}{{template "shared/user/namelink" .DefaultBranchBranch.DBBranch.Pusher}}{{end}}
{{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}}
@@ -102,7 +102,7 @@
{{svg "octicon-copy" 14}}
{{template "repo/commit_statuses" dict "Status" (index $.CommitStatus .DBBranch.CommitID) "Statuses" (index $.CommitStatuses .DBBranch.CommitID)}}
- {{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DBBranch.CommitID}} · {{RenderCommitMessage $.Context .DBBranch.CommitMessage ($.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DBBranch.CommitTime}}{{if .DBBranch.Pusher}} {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}} {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}
+ {{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha .DBBranch.CommitID}} · {{ctx.RenderUtils.RenderCommitMessage .DBBranch.CommitMessage ($.Repository.ComposeMetas ctx)}} · {{ctx.Locale.Tr "org.repo_updated"}} {{DateUtils.TimeSince .DBBranch.CommitTime}}{{if .DBBranch.Pusher}} {{template "shared/user/avatarlink" dict "user" .DBBranch.Pusher}} {{template "shared/user/namelink" .DBBranch.Pusher}}{{end}}
{{end}}
diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl
index 975d57324543a..b9d71917a1d1c 100644
--- a/templates/repo/commit_page.tmpl
+++ b/templates/repo/commit_page.tmpl
@@ -19,7 +19,7 @@
{{end}}