Skip to content

Commit 6a7bdab

Browse files
committed
Add complete server example
1 parent 4f2414e commit 6a7bdab

File tree

4 files changed

+71
-33
lines changed

4 files changed

+71
-33
lines changed

attributes/attributes.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@ func Dataset(key, value string) Attribute {
2222
}
2323

2424
func Dataset_(key, value string) Attribute {
25+
key_ := strings.Replace(key, "-", "_", -1)
2526
return Attribute{
2627
Data: map[string]string{},
27-
Templ: `{{define "Dataset"}}data-`+key+`="`+value+`"{{end}}`,
28-
Name: "Dataset",
28+
Templ: `{{define "Dataset_`+key_+`"}}data-`+key+`="`+value+`"{{end}}`,
29+
Name: "Dataset_"+key_,
2930
}
3031
}
3132

examples/main.go

Lines changed: 0 additions & 29 deletions
This file was deleted.

examples/server/main.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package main
2+
3+
import (
4+
"log"
5+
"net/http"
6+
7+
. "github.com/julvo/htmlgo"
8+
a "github.com/julvo/htmlgo/attributes"
9+
)
10+
11+
func main() {
12+
http.HandleFunc("/", indexHandler)
13+
log.Fatal(http.ListenAndServe(":8080", nil))
14+
}
15+
16+
func indexHandler(w http.ResponseWriter, req *http.Request) {
17+
fruit := []string{"Apple", "Banana", "Orange"}
18+
19+
fruitListItems := HTML("")
20+
for _, f := range fruit {
21+
fruitListItems += Li_(Text(f))
22+
}
23+
24+
content :=
25+
navbar(false) +
26+
Ul_(fruitListItems) +
27+
footer()
28+
29+
WriteTo(w, page("Home", content))
30+
}
31+
32+
func page(title string, content HTML) HTML {
33+
p :=
34+
Html5_(
35+
Head_(
36+
Title_(Text(title)),
37+
Meta(Attr(a.Charset_("utf-8"))),
38+
Meta(Attr(a.Name_("viewport"), a.Content_("width=device-width"), a.InitialScale_("1"))),
39+
Link(Attr(a.Rel_("stylesheet"), a.Href_("/static/css/main.min.css")))),
40+
Body_(
41+
content,
42+
Script(Attr(a.Src_("/static/js/main.min.js")), JS{})))
43+
44+
return p
45+
}
46+
47+
func navbar(isLoggedIn bool) HTML {
48+
var navItems HTML
49+
if !isLoggedIn {
50+
navItems = A(Attr(a.Href_("/login")), Text_("Login"))
51+
}
52+
53+
nav :=
54+
Nav_(
55+
Div_(navItems),
56+
Hr_())
57+
58+
return nav
59+
}
60+
61+
func footer() HTML {
62+
return Footer_(
63+
Hr_(),
64+
Text_("&copy Acme Ltd, 2019"))
65+
}

htmlgogen/templates/attributes/attributes.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@ func Dataset(key, value string) Attribute {
2222
}
2323

2424
func Dataset_(key, value string) Attribute {
25+
key_ := strings.Replace(key, "-", "_", -1)
2526
return Attribute{
2627
Data: map[string]string{},
27-
Templ: `{{define "Dataset"}}data-`+key+`="`+value+`"{{end}}`,
28-
Name: "Dataset",
28+
Templ: `{{define "Dataset_`+key_+`"}}data-`+key+`="`+value+`"{{end}}`,
29+
Name: "Dataset_"+key_,
2930
}
3031
}
3132

0 commit comments

Comments
 (0)