Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of concept: Template context function #24457

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions modules/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/translation"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/util"
Expand Down Expand Up @@ -216,6 +217,26 @@ func (ctx *Context) RedirectToFirst(location ...string) {

const tplStatus500 base.TplName = "status/500"

func (ctx *Context) newCtxFuncMap() template.FuncMap {
return template.FuncMap{
"CtxLocale": func(s string) string {
return ctx.Locale.Tr(s)
},
"CtxDateTime": func(format string, datetime any) template.HTML {
username := "(anonymous)"
if ctx.Doer != nil {
username = ctx.Doer.Name
}
s := fmt.Sprintf("PoC demo for %q: %s", html.EscapeString(username), timeutil.DateTime(format, datetime))
return template.HTML(s)
},
}
}

func (ctx *Context) renderHTML(w io.Writer, status int, name base.TplName, data map[string]any) error {
return ctx.Render.(*templates.HTMLRender).HTMLCtxFuncs(ctx.Resp, status, string(name), templates.BaseVars().Merge(data), ctx.newCtxFuncMap())
}

// HTML calls Context.HTML and renders the template to HTTP response
func (ctx *Context) HTML(status int, name base.TplName) {
log.Debug("Template: %s", name)
Expand All @@ -226,7 +247,7 @@ func (ctx *Context) HTML(status int, name base.TplName) {
ctx.Data["TemplateLoadTimes"] = func() string {
return strconv.FormatInt(time.Since(tmplStartTime).Nanoseconds()/1e6, 10) + "ms"
}
if err := ctx.Render.HTML(ctx.Resp, status, string(name), templates.BaseVars().Merge(ctx.Data)); err != nil {
if err := ctx.renderHTML(ctx.Resp, status, name, ctx.Data); err != nil {
if status == http.StatusInternalServerError && name == tplStatus500 {
ctx.PlainText(http.StatusInternalServerError, "Unable to find HTML templates, the template system is not initialized, or Gitea can't find your template files.")
return
Expand All @@ -239,7 +260,7 @@ func (ctx *Context) HTML(status int, name base.TplName) {
// RenderToString renders the template content to a string
func (ctx *Context) RenderToString(name base.TplName, data map[string]interface{}) (string, error) {
var buf strings.Builder
err := ctx.Render.HTML(&buf, http.StatusOK, string(name), data)
err := ctx.renderHTML(&buf, http.StatusOK, name, data)
return buf.String(), err
}

Expand Down
4 changes: 4 additions & 0 deletions modules/templates/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ func NewFuncMap() template.FuncMap {
return map[string]interface{}{
"DumpVar": dumpVar,

// ctx func
"CtxLocale": func(v ...any) any { panic("not implemented") },
"CtxDateTime": func(v ...any) any { panic("not implemented") },

// -----------------------------------------------------------------
// html/template related functions
"dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
Expand Down
19 changes: 19 additions & 0 deletions modules/templates/htmlrenderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"path/filepath"
Expand Down Expand Up @@ -53,6 +54,24 @@ func (h *HTMLRender) HTML(w io.Writer, status int, name string, data interface{}
return t.Execute(w, data)
}

func (h *HTMLRender) HTMLCtxFuncs(w io.Writer, status int, name string, data interface{}, ctxFuncMap template.FuncMap) error {
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)
}
tmpls := h.templates.Load()
if tmpls == nil {
return ErrTemplateNotInitialized
}
st, err := tmpls.Executor(name, NewFuncMap(), ctxFuncMap)
if err != nil {
return texttemplate.ExecError{Name: name, Err: err}
}
return st.Execute(w, data)
}

func (h *HTMLRender) TemplateLookup(name string) (TemplateExecutor, error) {
tmpls := h.templates.Load()
if tmpls == nil {
Expand Down
8 changes: 4 additions & 4 deletions modules/templates/scopedtmpl/scopedtmpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func (t *ScopedTemplate) Freeze() {
t.all.Funcs(m)
}

func (t *ScopedTemplate) Executor(name string, funcMap template.FuncMap) (TemplateExecutor, error) {
func (t *ScopedTemplate) Executor(name string, funcMaps ...template.FuncMap) (TemplateExecutor, error) {
t.scopedMu.RLock()
scopedTmplSet, ok := t.scopedTemplateSets[name]
t.scopedMu.RUnlock()
Expand All @@ -84,7 +84,7 @@ func (t *ScopedTemplate) Executor(name string, funcMap template.FuncMap) (Templa
if scopedTmplSet == nil {
return nil, fmt.Errorf("template %s not found", name)
}
return scopedTmplSet.newExecutor(funcMap), nil
return scopedTmplSet.newExecutor(funcMaps...), nil
}

type scopedTemplateSet struct {
Expand Down Expand Up @@ -216,14 +216,14 @@ func newScopedTemplateSet(all *template.Template, name string) (*scopedTemplateS
return ts, collectErr
}

func (ts *scopedTemplateSet) newExecutor(funcMap map[string]any) TemplateExecutor {
func (ts *scopedTemplateSet) newExecutor(funcMaps ...template.FuncMap) TemplateExecutor {
tmpl := texttemplate.New("")
tmplPtr := ptr[textTemplate](tmpl)
tmplPtr.execFuncs = map[string]reflect.Value{}
for k, v := range ts.execFuncs {
tmplPtr.execFuncs[k] = v
}
if funcMap != nil {
for _, funcMap := range funcMaps {
tmpl.Funcs(funcMap)
}
// after escapeTemplate, the html templates are also escaped text templates, so it could be added to the text template directly
Expand Down
2 changes: 2 additions & 0 deletions templates/devtest/ctxfunc.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Locale: {{CtxLocale "home"}}<br>
DateTime: {{CtxDateTime "full" "2001-02-03"}}<br>