-
-
Notifications
You must be signed in to change notification settings - Fork 19
Open
Description
Hello there!
I am currently learning templ, HTMX and AlpineJS and one of the things that I haven't really found an answer to is if I should be returning full pages at all time, or not. So, I have been playing with this simple bit of code:
package main
import (
"crypto/rand"
"encoding/base64"
"flag"
"fmt"
"net/http"
"github.com/a-h/templ"
"github.com/angelofallars/htmx-go"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
//go:generate go run github.com/a-h/templ/cmd/templ@latest generate
var bind = flag.String("bind", "127.0.0.1:3333", "Port to listen on")
func GenerateNonce() string {
b := make([]byte, 32) // 16 bytes (128 bits)
_, err := rand.Read(b)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(b)
}
func TemplNonce(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := templ.WithNonce(r.Context(), GenerateNonce())
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func main() {
flag.Parse()
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(TemplNonce)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
h := Hello()
if htmx.IsHTMX(r) {
res := htmx.NewResponse()
res.RenderTempl(ctx, w, h)
} else {
component := Layout()
component.Render(
templ.WithChildren(ctx, h),
w,
)
}
})
fmt.Println("Starting now")
http.ListenAndServe(*bind, r)
}
Components:
package main
script Greet(name string) {
alert(name)
}
templ Layout() {
<!DOCTYPE html>
<html>
<head>
<title>owo</title>
</head>
<body>
{ children... }
</body>
</html>
}
templ Hello() {
<p>This is a content o.o</p>
@Greet("ohey")
}
Nothing too complex; but basically I wonder if making a layout and stuff is even needed or if I should just call @Layout() { ... }
instead.
Mind giving your input on this?
Thank you very much!
Kind regards,
Ingwie
Metadata
Metadata
Assignees
Labels
No labels