about summary refs log tree commit diff stats
path: root/examples/simple/simple.go
blob: 535fa6e13014a1415d7db5d85c30121849a3d863 (plain)
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
package main

import (
	"net/http"
	"time"

	g "github.com/maragudk/gomponents"
	c "github.com/maragudk/gomponents/components"
	h "github.com/maragudk/gomponents/html"
)

func main() {
	_ = http.ListenAndServe("localhost:8080", http.HandlerFunc(handler))
}

func handler(w http.ResponseWriter, r *http.Request) {
	p := page(props{
		title: r.URL.Path,
		path:  r.URL.Path,
	})
	_ = p.Render(w)
}

type props struct {
	title string
	path  string
}

func page(p props) g.Node {
	return h.Document(
		h.HTML(h.Lang("en"),
			h.Head(
				h.TitleEl(p.title),
				h.StyleEl(h.Type("text/css"),
					g.Raw(".is-active{font-weight: bold}"),
					g.Raw("ul.nav { list-style-type: none; margin: 0; padding: 0; overflow: hidden; }"),
					g.Raw("ul.nav li { display: block;  padding: 8px; float: left; }"),
				),
			),
			h.Body(
				navbar(navbarProps{path: p.path}),
				h.Hr(),
				h.H1(p.title),
				h.P(g.Textf("Welcome to the page at %v.", p.path)),
				h.P(g.Textf("Rendered at %v", time.Now())),
			),
		),
	)
}

type navbarProps struct {
	path string
}

func navbar(props navbarProps) g.Node {
	items := []struct {
		path string
		text string
	}{
		{"/", "Home"},
		{"/foo", "Foo"},
		{"/bar", "Bar"},
	}
	lis := g.Map(len(items), func(i int) g.Node {
		item := items[i]
		return h.Li(
			h.A(item.path, c.Classes(map[string]bool{"is-active": props.path == item.path}), g.Text(item.text)),
		)
	})
	return h.Ul(h.Class("nav"), g.Group(lis))
}