From 27e6e266041e8969357d5100ead3f2a653fadf87 Mon Sep 17 00:00:00 2001 From: sunfmin Date: Fri, 3 Jan 2020 15:45:14 +0800 Subject: [PATCH] Add Iff to pass body as an func in --- README.md | 24 ++++++++++++++++++++++++ example_test.go | 26 ++++++++++++++++++++++++++ if.go | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) diff --git a/README.md b/README.md index 3211a38..2631b82 100644 --- a/README.md +++ b/README.md @@ -314,5 +314,29 @@ An example show how to set styles //
``` +An example to use If, `Iff` is for body to passed in as an func for the body depends on if condition not to be nil, `If` is for directly passed in HTMLComponent +```go + type Person struct { + Age int + } + var p *Person + + name := "Leon" + comp := Div( + Iff(p != nil && p.Age > 18, func() HTMLComponent { + return Div().Text(name + ": Age > 18") + }).ElseIf(p == nil, func() HTMLComponent { + return Div().Text("No person named " + name) + }).Else(func() HTMLComponent { + return Div().Text(name + ":Age <= 18") + }), + ) + Fprint(os.Stdout, comp, context.TODO()) + //Output: + //
+ //
No person named Leon
+ //
+``` + diff --git a/example_test.go b/example_test.go index 7866184..1f1aad4 100644 --- a/example_test.go +++ b/example_test.go @@ -358,3 +358,29 @@ func ExampleTag_08styles() { //Output: //
} + +/* +An example to use If, `Iff` is for body to passed in as an func for the body depends on if condition not to be nil, `If` is for directly passed in HTMLComponent +*/ +func ExampleTag_09iff() { + type Person struct { + Age int + } + var p *Person + + name := "Leon" + comp := Div( + Iff(p != nil && p.Age > 18, func() HTMLComponent { + return Div().Text(name + ": Age > 18") + }).ElseIf(p == nil, func() HTMLComponent { + return Div().Text("No person named " + name) + }).Else(func() HTMLComponent { + return Div().Text(name + ":Age <= 18") + }), + ) + Fprint(os.Stdout, comp, context.TODO()) + //Output: + //
+ //
No person named Leon
+ //
+} diff --git a/if.go b/if.go index 87db45d..c32746c 100644 --- a/if.go +++ b/if.go @@ -42,3 +42,44 @@ func (b *IfBuilder) MarshalHTML(ctx context.Context) (r []byte, err error) { } return HTMLComponents(b.comps).MarshalHTML(ctx) } + +type IfFuncBuilder struct { + f func() HTMLComponent + set bool +} + +func Iff(v bool, f func() HTMLComponent) (r *IfFuncBuilder) { + r = &IfFuncBuilder{} + if v { + r.f = f + r.set = true + } + return +} + +func (b *IfFuncBuilder) ElseIf(v bool, f func() HTMLComponent) (r *IfFuncBuilder) { + if b.set { + return b + } + if v { + b.f = f + b.set = true + } + return b +} + +func (b *IfFuncBuilder) Else(f func() HTMLComponent) (r *IfFuncBuilder) { + if b.set { + return b + } + b.set = true + b.f = f + return b +} + +func (b *IfFuncBuilder) MarshalHTML(ctx context.Context) (r []byte, err error) { + if b.f == nil { + return + } + return b.f().MarshalHTML(ctx) +}