summaryrefslogtreecommitdiffstats
path: root/modules
diff options
context:
space:
mode:
Diffstat (limited to 'modules')
-rw-r--r--modules/context/context_response.go14
-rw-r--r--modules/templates/helper.go6
-rw-r--r--modules/templates/helper_test.go4
3 files changed, 23 insertions, 1 deletions
diff --git a/modules/context/context_response.go b/modules/context/context_response.go
index d9102b77bd..829bca1f59 100644
--- a/modules/context/context_response.go
+++ b/modules/context/context_response.go
@@ -90,6 +90,20 @@ func (ctx *Context) HTML(status int, name base.TplName) {
}
}
+// JSONTemplate renders the template as JSON response
+// keep in mind that the template is processed in HTML context, so JSON-things should be handled carefully, eg: by JSEscape
+func (ctx *Context) JSONTemplate(tmpl base.TplName) {
+ t, err := ctx.Render.TemplateLookup(string(tmpl), nil)
+ if err != nil {
+ ctx.ServerError("unable to find template", err)
+ return
+ }
+ ctx.Resp.Header().Set("Content-Type", "application/json")
+ if err = t.Execute(ctx.Resp, ctx.Data); err != nil {
+ ctx.ServerError("unable to execute template", err)
+ }
+}
+
// RenderToString renders the template content to a string
func (ctx *Context) RenderToString(name base.TplName, data map[string]any) (string, error) {
var buf strings.Builder
diff --git a/modules/templates/helper.go b/modules/templates/helper.go
index 9ff5d8927f..6e42594b0b 100644
--- a/modules/templates/helper.go
+++ b/modules/templates/helper.go
@@ -38,7 +38,7 @@ func NewFuncMap() template.FuncMap {
"Safe": Safe,
"Escape": Escape,
"QueryEscape": url.QueryEscape,
- "JSEscape": template.JSEscapeString,
+ "JSEscape": JSEscapeSafe,
"Str2html": Str2html, // TODO: rename it to SanitizeHTML
"URLJoin": util.URLJoin,
"DotEscape": DotEscape,
@@ -211,6 +211,10 @@ func Escape(s any) template.HTML {
panic(fmt.Sprintf("unexpected type %T", s))
}
+func JSEscapeSafe(s string) template.HTML {
+ return template.HTML(template.JSEscapeString(s))
+}
+
func RenderEmojiPlain(s any) any {
switch v := s.(type) {
case string:
diff --git a/modules/templates/helper_test.go b/modules/templates/helper_test.go
index ec83e9ac33..739a92f34f 100644
--- a/modules/templates/helper_test.go
+++ b/modules/templates/helper_test.go
@@ -52,3 +52,7 @@ func TestSubjectBodySeparator(t *testing.T) {
"",
"Insuficient\n--\nSeparators")
}
+
+func TestJSEscapeSafe(t *testing.T) {
+ assert.EqualValues(t, `\u0026\u003C\u003E\'\"`, JSEscapeSafe(`&<>'"`))
+}