htmgo/framework/h/conditionals.go

79 lines
2.1 KiB
Go
Raw Normal View History

2024-09-21 03:59:07 +00:00
package h
2024-10-26 02:59:17 +00:00
// If returns the node if the condition is true, otherwise returns an empty element
2024-09-21 03:59:07 +00:00
func If(condition bool, node Ren) Ren {
if condition {
return node
} else {
return Empty()
}
}
2024-10-26 02:59:17 +00:00
// Ternary returns the first argument if the second argument is true, otherwise returns the third argument
2024-09-21 16:52:56 +00:00
func Ternary[T any](value bool, a T, b T) T {
2024-09-22 16:25:18 +00:00
return IfElse(value, a, b)
2024-09-21 16:52:56 +00:00
}
2024-10-26 02:59:17 +00:00
// ElementIf returns the element if the condition is true, otherwise returns an empty element
2024-09-23 15:57:59 +00:00
func ElementIf(condition bool, element *Element) *Element {
if condition {
return element
} else {
return Empty()
}
}
2024-10-26 02:59:17 +00:00
// IfElseE returns element if condition is true, otherwise returns element2
2024-09-28 02:29:53 +00:00
func IfElseE(condition bool, element *Element, element2 *Element) *Element {
if condition {
return element
} else {
return element2
}
}
2024-10-26 02:59:17 +00:00
// IfElse returns node if condition is true, otherwise returns node2
2024-09-22 16:25:18 +00:00
func IfElse[T any](condition bool, node T, node2 T) T {
2024-09-21 03:59:07 +00:00
if condition {
return node
} else {
return node2
}
}
2024-10-26 02:59:17 +00:00
// IfElseLazy returns node if condition is true, otherwise returns the result of cb2
// This is useful if you want to lazily evaluate a node based on a condition
// For example, If you are rendering a component that requires specific data,
// you can use this to only load the component if the data is available
2024-09-22 16:25:18 +00:00
func IfElseLazy[T any](condition bool, cb1 func() T, cb2 func() T) T {
2024-09-21 03:59:07 +00:00
if condition {
return cb1()
} else {
return cb2()
}
}
2024-10-26 02:59:17 +00:00
// IfHtmxRequest returns the node if the request is an htmx request, otherwise returns an empty element
2024-09-21 03:59:07 +00:00
func IfHtmxRequest(ctx *RequestContext, node Ren) Ren {
if ctx.isHxRequest {
2024-09-21 03:59:07 +00:00
return node
}
return Empty()
}
2024-09-21 16:52:56 +00:00
2024-10-26 02:59:17 +00:00
// ClassIf returns the class attribute if the condition is true, otherwise returns an empty element
2024-09-21 16:52:56 +00:00
func ClassIf(condition bool, value string) Ren {
if condition {
return Class(value)
}
return Empty()
}
2024-09-24 19:51:46 +00:00
2024-10-26 02:59:17 +00:00
// AttributeIf returns the attribute if the condition is true, otherwise returns an empty element
2024-09-24 19:51:46 +00:00
func AttributeIf(condition bool, name string, value string) Ren {
if condition {
return Attribute(name, value)
}
return Empty()
}