Documentation menu

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.

Copy
1h.Div(
2	h.If(task.CompletedAt != nil, h.Span(h.Text("✓"))),
3)

Choose which partial handles a request with h.Ternary.

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.

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.

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())
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)
Copy