Skip to content

Commit

Permalink
Add Iff to pass body as an func in
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfmin committed Jan 3, 2020
1 parent 6e46476 commit 27e6e26
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,5 +314,29 @@ An example show how to set styles
// <div style='background-color:red; border:1px solid red; color:blue;'></div>
```

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:
// <div>
// <div>No person named Leon</div>
// </div>
```



26 changes: 26 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,3 +358,29 @@ func ExampleTag_08styles() {
//Output:
// <div style='background-color:red; border:1px solid red; color:blue;'></div>
}

/*
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:
// <div>
// <div>No person named Leon</div>
// </div>
}
41 changes: 41 additions & 0 deletions if.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 27e6e26

Please sign in to comment.