Skip to content

Commit

Permalink
Adding the Sequence function to the template context
Browse files Browse the repository at this point in the history
  • Loading branch information
matang28 committed Feb 8, 2021
1 parent ef2b399 commit b0bf5f2
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
40 changes: 40 additions & 0 deletions internal/data/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package data

import (
"github.com/AdikaStyle/go-report-builder/internal/models"
"github.com/stretchr/testify/assert"
"testing"
)

func TestTemplateContext_Sequence(t *testing.T) {
template := `{{- range $i, $item := .Sequence 3 }}
a
{{- end }}`

te := NewGolangTemplateEngine()
rendered, err := te.Render([]byte(template), &models.TemplateContext{})

assert.Nil(t, err)
assert.NotNil(t, rendered)
assert.EqualValues(t, "\na\na\na", string(rendered))
}

func TestTemplateContext_Sequence2(t *testing.T) {
template := `{{- range $i, $item := .Sequence 10 }}
{{- if lt $i (len $.Values.array) }}
{{ index $.Values.array $i }}
{{- else }}
0
{{- end }}
{{- end }}`

te := NewGolangTemplateEngine()
rendered, err := te.Render([]byte(template), &models.TemplateContext{Values: map[string]interface{}{
"array": []int{4, 5, 6},
}})

assert.Nil(t, err)
assert.NotNil(t, rendered)
assert.EqualValues(t, "\n4\n5\n6\n0\n0\n0\n0\n0\n0\n0", string(rendered))
}
8 changes: 8 additions & 0 deletions internal/models/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,11 @@ package models
type TemplateContext struct {
Values interface{}
}

func (ctx *TemplateContext) Sequence(size int) []int {
var out []int
for i := 0; i < size; i++ {
out = append(out, i+1)
}
return out
}
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func main() {
module := cmd.NewModule(config)
logrus.Info("module built successfully")

logrus.Info("server started at port: %d...", config.ServerPort)
logrus.Infof("server started at port: %d...", config.ServerPort)
panicOnError(module.Server.Start())
}

Expand Down

0 comments on commit b0bf5f2

Please sign in to comment.