Skip to content

Commit

Permalink
Merge pull request #1 from AccentDesign/add-if-element-839
Browse files Browse the repository at this point in the history
add if helper func
  • Loading branch information
stuartaccent authored Jan 22, 2025
2 parents adc2188 + 1ef485c commit e3315e0
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
28 changes: 28 additions & 0 deletions examples/conditional/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"context"
"fmt"
"github.com/accentdesign/gtml"
"os"
"time"
)

func Nav(isLoggedIn bool) *gtml.Element {
return gtml.UL(
gtml.NA,
gtml.LI(gtml.NA, gtml.A(gtml.NA, gtml.Text("Home"))),
gtml.If(isLoggedIn, gtml.LI(gtml.NA, gtml.A(gtml.NA, gtml.Text("Profile")))),
)
}

func main() {
defer func(start time.Time) {
fmt.Println("")
fmt.Println(time.Since(start))
}(time.Now())

nav := Nav(true)

_ = nav.Render(context.Background(), os.Stdout)
}
9 changes: 9 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package gtml

// If returns the element if the condition is true, otherwise returns an empty element.
func If(condition bool, element *Element) *Element {
if condition {
return element
}
return Empty()
}
26 changes: 26 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package gtml

import "testing"

// Test the If function with true and false conditions.
func TestIfFunction(t *testing.T) {
tests := []struct {
name string
condition bool
element *Element
expected string
}{
{"IfTrue", true, Div(NA, Text("Visible")), `<div>Visible</div>`},
{"IfFalse", false, Div(NA, Text("Visible")), ``},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
node := If(tt.condition, tt.element)
output := renderElement(t, node)
if output != tt.expected {
t.Errorf("Expected %q, got %q", tt.expected, output)
}
})
}
}

0 comments on commit e3315e0

Please sign in to comment.