Files
go-htmx-templ/app/handlers/interactive.go
2024-01-21 21:06:26 +01:00

88 lines
2.1 KiB
Go

package handlers
import (
"strconv"
"strings"
"templ-tests/app/data"
"templ-tests/app/templates"
"templ-tests/app/types"
"github.com/gin-gonic/gin"
)
var pcInteractive templates.PageContext = templates.PageContext{
Title: "Welcome to the demo - Interactive",
ActivePage: "interactive",
}
func Interactive(c *gin.Context) {
templates.Interactive(pcInteractive, data.CatBreeds).Render(c, c.Writer)
}
func InteractiveSwapContent(c *gin.Context) {
contentIndexStr := c.Query("content")
contentIndex, err := strconv.Atoi(contentIndexStr)
if err != nil {
contentIndex = 0
}
templates.InteractiveSwapContent(pcInteractive, contentIndex).Render(c, c.Writer)
}
func FilterCatBreeds(c *gin.Context) {
breedQuery := strings.ToLower(c.Query("breed"))
countryQuery := c.Query("country")
var catBreeds []types.CatBreed = []types.CatBreed{}
for _, cb := range data.CatBreeds {
appendToList :=
(len(breedQuery) > 0 &&
strings.Contains(strings.ToLower(cb.Breed), breedQuery) ||
len(breedQuery) == 0) &&
((len(countryQuery) > 0 &&
cb.Country == countryQuery) ||
len(countryQuery) == 0)
if appendToList {
catBreeds = append(catBreeds, cb)
}
}
templates.RenderCatBreedsTable(catBreeds).Render(c, c.Writer)
}
func ValidateForm(c *gin.Context) {
content := templates.ValidateFormContent{
Validated: true,
NumValue: c.PostForm("number-value"),
StrValue: c.PostForm("string-value"),
}
numValue, err := strconv.Atoi(content.NumValue)
if err != nil {
content.HasNumValueError = true
content.NumValueError = "This is not valid number"
}
if !content.HasNumValueError {
if numValue < 0 {
content.HasNumValueError = true
content.NumValueError = "Value is less than 0"
}
if numValue > 100 {
content.HasNumValueError = true
content.NumValueError = "Value is greater than 100"
}
}
if len(content.StrValue) < 5 {
content.HasStrValueError = true
content.StrValueError = "String length is less than 5"
}
if len(content.StrValue) > 10 {
content.HasStrValueError = true
content.StrValueError = "String length is more than 10"
}
templates.RenderInteractiveForm(content).Render(c, c.Writer)
}