Skip to content

Commit 3e4d4ae

Browse files
committed
Implement contextually escaped javascript
1 parent 83b9727 commit 3e4d4ae

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

htmlgogen/templates/elements.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import (
44
"fmt"
55
"strings"
66
"html"
7-
_"html/template"
7+
"html/template"
8+
"bytes"
89

910
a "github.com/julvo/htmlgo/attributes"
1011
)
@@ -23,7 +24,7 @@ func insertAttributes(attrs []a.Attribute) string {
2324
return s
2425
}
2526

26-
func insertChildren(children []HTML) string {
27+
func insertChildren(children ...HTML) string {
2728
s := ""
2829
for _, c := range children {
2930
s += string(c)
@@ -38,7 +39,7 @@ func indent(s, indentation string) string {
3839
func Element(tag string, attrs []a.Attribute, children ...HTML) HTML {
3940
return HTML(
4041
"\n<" + tag + insertAttributes(attrs) + ">" +
41-
indent(insertChildren(children), " ") +
42+
indent(insertChildren(children...), " ") +
4243
"\n</" + tag + ">")
4344
}
4445

@@ -69,7 +70,23 @@ func Doctype(t string) HTML {
6970
const DoctypeHtml5 HTML = "<!DOCTYPE HTML>"
7071

7172
func Script(attrs []a.Attribute, js JS) HTML {
72-
return HTML("")
73+
if js.data == nil {
74+
return Element("script", attrs, HTML("\n" + js.templ))
75+
}
76+
77+
// TODO set verbosity level to enable logging
78+
t, err := template.New("_").Parse(
79+
"\n<script" + insertAttributes(attrs) + ">" +
80+
indent("\n" + js.templ, " ") + "\n</script>")
81+
if err != nil {
82+
return Element("script", attrs)
83+
}
84+
buf := new(bytes.Buffer)
85+
err = t.Execute(buf, js.data)
86+
if err != nil {
87+
return Element("script", attrs)
88+
}
89+
return HTML(buf.String())
7390
}
7491

7592
func Script_(js JS) HTML {

0 commit comments

Comments
 (0)