Golang How to create a loop function using the html / template package

I am trying to implement loop as a custom function. It takes the number of iterations and contents between braces, then it must iterate over the contents between brackets n times. 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}} 

Exit

 <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 the standard text/template functionality does not allow you to simply iterate over the contents between a curly brace. Yes, we can do this through the range action, passing through the "external" data.

+5
source share
1 answer

You can use range for 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) } 
+9
source

Source: https://habr.com/ru/post/1214903/


All Articles