go - Looping over a map using range, only iterate once -


i need iterate on loop once in golang template, looping on keys want stop after single iteration.

how can this?

{{range .users}} <div>   {{.name}} </div> {{end}} 

two solutions; either check index 0 when looping:

{{range $index, $element := . }}{{if eq $index 0 -}} item: {{$element}} {{end}}{{end -}} 

or define "first" function takes slice , truncates length 1.

{{range first .}} item: {{.}} {{end}} 

here's complete code demonstrates both, can try on playground.

package main  import (     "fmt"     "os"     "text/template" )  var t = template.must(template.new("x").parse(     "[{{range $index, $element := . }}{{if eq $index 0 -}}{{$element}}{{end}}{{end -}}]"))  var funcs = map[string]interface{}{     "first": func(arg []string) []string {         if len(arg) > 0 {             return arg[:1]         }         return nil     }, }  var t2 = template.must(template.new("x").funcs(funcs).parse(     "[{{range first . }}{{.}}{{end -}}]"))  func main() {     tmpls := []*template.template{t, t2}     i, t := range tmpls {         fmt.println("template", i)         := []string{"one", "two", "three"}         j := 0; j < len(a); j++ {             fmt.println("with input slice of length", j)             t.execute(os.stdout, a[:j])             fmt.println()         }         fmt.println()     } } 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -