summaryrefslogtreecommitdiffstats
path: root/modules/templates/htmlrenderer.go
diff options
context:
space:
mode:
authorwxiaoguang <wxiaoguang@gmail.com>2023-08-08 09:22:47 +0800
committerGitHub <noreply@github.com>2023-08-08 01:22:47 +0000
commit69130532239ee7ade82977f456c12826e1adeb1e (patch)
tree81b8131bedc592af753481b7d222263b2c2655dc /modules/templates/htmlrenderer.go
parent0c6ae61229bce9d9ad3d359cee927464968a2dd1 (diff)
downloadgitea-69130532239ee7ade82977f456c12826e1adeb1e.tar.gz
gitea-69130532239ee7ade82977f456c12826e1adeb1e.zip
Start using template context function (#26254)
Before: * `{{.locale.Tr ...}}` * `{{$.locale.Tr ...}}` * `{{$.root.locale.Tr ...}}` * `{{template "sub" .}}` * `{{template "sub" (dict "locale" $.locale)}}` * `{{template "sub" (dict "root" $)}}` * ..... With context function: only need to `{{ctx.Locale.Tr ...}}` The "ctx" could be considered as a super-global variable for all templates including sub-templates. To avoid potential risks (any bug in the template context function package), this PR only starts using "ctx" in "head.tmpl" and "footer.tmpl" and it has a "DataRaceCheck". If there is anything wrong, the code can be fixed or reverted easily.
Diffstat (limited to 'modules/templates/htmlrenderer.go')
-rw-r--r--modules/templates/htmlrenderer.go12
1 files changed, 7 insertions, 5 deletions
diff --git a/modules/templates/htmlrenderer.go b/modules/templates/htmlrenderer.go
index d470435b63..5ab46cb13a 100644
--- a/modules/templates/htmlrenderer.go
+++ b/modules/templates/htmlrenderer.go
@@ -6,6 +6,7 @@ package templates
import (
"bufio"
"bytes"
+ "context"
"errors"
"fmt"
"io"
@@ -39,27 +40,28 @@ var (
var ErrTemplateNotInitialized = errors.New("template system is not initialized, check your log for errors")
-func (h *HTMLRender) HTML(w io.Writer, status int, name string, data any) error {
+func (h *HTMLRender) HTML(w io.Writer, status int, name string, data any, ctx context.Context) error { //nolint:revive
if respWriter, ok := w.(http.ResponseWriter); ok {
if respWriter.Header().Get("Content-Type") == "" {
respWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
}
respWriter.WriteHeader(status)
}
- t, err := h.TemplateLookup(name)
+ t, err := h.TemplateLookup(name, ctx)
if err != nil {
return texttemplate.ExecError{Name: name, Err: err}
}
return t.Execute(w, data)
}
-func (h *HTMLRender) TemplateLookup(name string) (TemplateExecutor, error) {
+func (h *HTMLRender) TemplateLookup(name string, ctx context.Context) (TemplateExecutor, error) { //nolint:revive
tmpls := h.templates.Load()
if tmpls == nil {
return nil, ErrTemplateNotInitialized
}
-
- return tmpls.Executor(name, NewFuncMap())
+ m := NewFuncMap()
+ m["ctx"] = func() any { return ctx }
+ return tmpls.Executor(name, m)
}
func (h *HTMLRender) CompileTemplates() error {