5

I'm trying to implement loop as custom function. It takes number of iterations and content between curly brackets, then it should iterate content between brackets n times. Please, see example:

main.go

template.Must(template.ParseFiles("palette.html")).Funcs(template.FuncMap{
        "loop": func(n int, content string) string {
            var r string
            for i := 0; i <= n; i++ {
                r += content
            }
            return r
        },
    }).ExecuteTemplate(rw, index, nil)

index.html

{{define "index"}}
<div class="row -flex palette">
  {{loop 16}}
    <div class="col-2"></div>
  {{end}}
</div>
{{end}}

Output

<div class="row -flex palette">
    <div class="col-2"></div>
    <div class="col-2"></div>
    <div class="col-2"></div>
    <div class="col-2"></div>
    ... 16 times
</div>

Is it possible to implement it? The motivation is that standard functionality of the text/template doesn't allow just to iterate content between curly bracket. Yes we can do it by range action going through "outside" data.

1 Answer 1

12

You can use range on a function that returns a slice. http://play.golang.org/p/FCuLkEHaZn

package main

import (
    "html/template"
    "os"
)

func main() {
    html := `
<div class="row -flex palette">
  {{range loop 16}}
    <div class="col-2"></div>
  {{end}}
</div>`
    tmpl := template.Must(template.New("test").Funcs(template.FuncMap{
        "loop": func(n int) []struct{} {
            return make([]struct{}, n)
        },
    }).Parse(html))
    tmpl.Execute(os.Stdout, nil)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good idea! Thus there is no way to get content from curly brackets?)
If you aren't using the slice elements, it is more efficient to use an empty struct. play.golang.org/p/_jRV62bOB3 This way you only allocate a slice header (constant size) instead of n elements.
yeap! you are absolutely right!) @Innominate, please update your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.