How to update field value in a Go template -


i have following case, passing struct containing map template:

package main  import (     "log"     "os"     "text/template" )  var fns = template.funcmap{     "plus1": func(x int) int {         return x + 1     }, }  type codec struct {     names map[string]string     count int }  func main() {     := map[string]string{"one": "1",         "two":   "2",         "three": "3"}      t := template.must(template.new("abc").funcs(fns).parse(`{{$l := len .names}}{{range $k, $v := .names}}{{if ne (plus1 $.count) $l}}{{$k}} {{$v}} {{end}}{{end}}.`))      err := t.execute(os.stdout, codec{a, 0})     if err != nil {         log.println(err)     } } 

i increment count field of codec can know how many items of map i've seen.

you can define method on struct:

type codec struct {     names map[string]string     count int }  func (c *codec) incandget() int {     c.count++     return c.count } 

calling template:

c := &codec{count: 2} t := template.must(template.new("").parse(`{{.incandget}} {{.incandget}}`)) t.execute(os.stdout, c) 

output (try on go playground):

3 4 

note work, method needs pointer receiver (func (c *codec) incandget()) , have pass pointer template.execute() (c pointer in our example: c := &codec{count: 2}).

if don't want result counting, define have string return type , return empty string "":

func (c *codec) inc() string {     c.count++     return "" } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -