basic example with two types of templates

This commit is contained in:
Nickiel12 2024-01-12 16:34:26 -08:00
parent 100f482de9
commit 8709901ef9
6 changed files with 32 additions and 5 deletions

1
db.go
View file

@ -34,7 +34,6 @@ func db_get_transactions(transactions *[]Transaction, r *GetTransactionPaginatio
func db_new_transaction(transaction Transaction) error {
db, err := sqlx.Connect(DB_TYPE, DB_CONNECTION_STRING)
if err != nil {
log.Info()
log.Fatal().
Err(err).
Msg("Fatal error in db_get_transactions\nCannot connect to server")

View file

@ -73,9 +73,6 @@
pkgs = nixpkgsFor.${system};
in {
default = pkgs.mkShell {
shellHook = ''
alias gotest='templ generate;go run . -d'
'';
buildInputs = with pkgs; [
air # live go app reloading
go

View file

@ -30,7 +30,7 @@ func hello(name string) templ.Component {
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/index.templ`, Line: 3, Col: 21}
return templ.Error{Err: templ_7745c5c3_Err, FileName: `web/hello.templ`, Line: 3, Col: 21}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {

View file

@ -2,6 +2,7 @@ package web
import (
"net/http"
"html/template"
"context"
@ -10,6 +11,12 @@ import (
"github.com/rs/zerolog/log"
)
const TemplateDir = "./web/templates/"
type IndexData struct {
Title string
}
func SetLogLevel(level zerolog.Level) {
zerolog.SetGlobalLevel(level)
}
@ -17,10 +24,22 @@ func SetLogLevel(level zerolog.Level) {
func WebRouter() http.Handler {
r := chi.NewRouter()
r.Get("/", getIndex)
r.Get("/hello", getHello)
return r
}
func getIndex(w http.ResponseWriter, req *http.Request) {
index, err := template.ParseFiles(TemplateDir + "index.html")
if err != nil {
log.Fatal().
Err(err).
Msg("Fatal error reading index template")
}
err = index.Execute(w, IndexData{Title: "thetitle"})
}
func getHello(w http.ResponseWriter, req *http.Request) {
log.Debug().Msg("Got index")
component := hello("Nick")
component.Render(context.Background(), w)

12
web/templates/index.html Normal file
View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Title}}</title>
</head>
<body>
<h1>Hello World!</h1>
<a href="/hello">Hello you!</a>
</body>
</html>