-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_basic_test.go
89 lines (73 loc) · 1.83 KB
/
example_basic_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package temple_test
import (
"context"
"log/slog"
"os"
"impractical.co/temple"
)
type MySite struct {
// anonymously embedding a *CachedSite makes MySite a Site implementation
*temple.CachedSite
// a configurable title for our site
Title string
}
type HomePage struct {
Layout BaseLayout
}
func (HomePage) Templates(_ context.Context) []string {
return []string{"home.html.tmpl"}
}
func (h HomePage) UseComponents(_ context.Context) []temple.Component {
return []temple.Component{
h.Layout,
}
}
func (HomePage) Key(_ context.Context) string {
return "home.html.tmpl"
}
func (h HomePage) ExecutedTemplate(_ context.Context) string {
return h.Layout.BaseTemplate()
}
type BaseLayout struct {
}
func (b BaseLayout) Templates(_ context.Context) []string {
return []string{b.BaseTemplate()}
}
func (BaseLayout) BaseTemplate() string {
return "base.html.tmpl"
}
func ExampleRender_basic() {
// normally you'd use something like embed.FS or os.DirFS for this
// for example purposes, we're just hardcoding values
var templates = staticFS{
"home.html.tmpl": `{{ define "body" }}Hello, world. This is my home page.{{ end }}`,
"base.html.tmpl": `
<!doctype html>
<html lang="en">
<head>
<title>{{ .Site.Title }}</title>
</head>
<body>
{{ block "body" . }}{{ end }}
</body>
</html>`,
}
// usually the context comes from the request, but here we're building it from scratch and adding a logger
ctx := temple.LoggingContext(context.Background(), slog.Default())
site := MySite{
CachedSite: temple.NewCachedSite(templates),
Title: "My Example Site",
}
page := HomePage{Layout: BaseLayout{}}
temple.Render(ctx, os.Stdout, site, page)
//Output:
// <!doctype html>
// <html lang="en">
// <head>
// <title>My Example Site</title>
// </head>
// <body>
// Hello, world. This is my home page.
// </body>
// </html>
}