Documentation menu
Getting Started
Core Concepts
Control
Interactivity
Pushing Data
HTMX Extensions
Miscellaneous
Configuration
If / Else Statements
If / else statements are useful when you want to conditionally render attributes or elements / components.
htmgo provides a couple of utilities to do so:
Render an icon if the task is complete.
h.Div(
h.If(task.CompletedAt != nil, h.Span(h.Text("✓"))),
)
Copy
1h.Div(
2 h.If(task.CompletedAt != nil, h.Span(h.Text("✓"))),
3)Choose which partial handles a request with h.Ternary.
h.Button(
h.Type("button"),
h.PostPartialWithQs(
h.Ternary(editing, SaveEditing, StartEditing),
h.NewQs("id", recordID),
),
h.Text(h.Ternary(editing, "Save", "Edit")),
)
Copy
1h.Button(
2 h.Type("button"),
3 h.PostPartialWithQs(
4 h.Ternary(editing, SaveEditing, StartEditing),
5 h.NewQs("id", recordID),
6 ),
7 h.Text(h.Ternary(editing, "Save", "Edit")),
8)Apply multiple classes based on a condition.
h.ClassX("w-10 h-10 border rounded-full", h.ClassMap{
"border-green-500": task.CompletedAt != nil,
"border-slate-400": task.CompletedAt == nil,
})
Copy
1h.ClassX("w-10 h-10 border rounded-full", h.ClassMap{
2 "border-green-500": task.CompletedAt != nil,
3 "border-slate-400": task.CompletedAt == nil,
4})Apply a single class based on a condition.
h.Div(
h.ClassIf(task.CompletedAt != nil, "border-green-500"),
)
Copy
1h.Div(
2 h.ClassIf(task.CompletedAt != nil, "border-green-500"),
3)Render different elements based on a condition.
h.IfElse(editing, EditTaskForm(), ViewTask())
h.IfElse(editing, EditTaskForm(), ViewTask())Copy
Go evaluates both EditTaskForm() and ViewTask() before calling h.IfElse.
Pass the functions to h.IfElseLazy to call only the selected one.
h.IfElseLazy(editing, EditTaskForm, ViewTask)
h.IfElseLazy(editing, EditTaskForm, ViewTask)Copy