Getting Started
Core Concepts
Control
Interactivity
Performance
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:
Example: Rendering an icon if the task is complete
1h.Div(
2 h.If(
3 task.CompletedAt != nil,
4 CompleteIcon()
5 )
6)
Example: Using ternary operator to call different partials based on a condition
1h.Div(
2 h.PostPartialWithQs(
3 h.Ternary(!editing, StartEditing, SaveEditing),
4 h.NewQs("id", record.Id),
5 ),
6)
Example: Rendering multiple classes based on a condition
1h.ClassX("w-10 h-10 border rounded-full", map[string]bool {
2 "border-green-500": task.CompletedAt != nil,
3 "border-slate-400": task.CompletedAt == nil,
4})
Example: Rendering a single class based on a condition
1h.Div(
2 h.ClassIf(task.CompletedAt != nil, "border-green-500"),
3)
Example: Rendering different elements based on a condition
h.IfElse(editing, EditTaskForm(), ViewTask())
Note: This will execute both EditTaskForm and ViewTask, no matter if the condition is true or false, since a function is being called here.
If you do not want to call the function at all unless the condition is true, use h.IfElseLazy
h.IfElseLazy(editing, EditTaskForm, ViewTask)