dougan6402 2016-01-27 09:57
浏览 53
已采纳

如何在Go模板中更新字段值

I have the following case, where I am passing a struct containing a map to a 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() {
    a := 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 would like to increment the Count field of codec so that I can know how many items of the map I've seen.

  • 写回答

2条回答 默认 最新

  • doukongyong44772 2016-01-27 11:13
    关注

    You can simply define a method on your struct:

    type codec struct {
        Names map[string]string
        Count int
    }
    
    func (c *codec) IncAndGet() int {
        c.Count++
        return c.Count
    }
    

    Calling it from a template:

    c := &codec{Count: 2}
    t := template.Must(template.New("").Parse(`{{.IncAndGet}} {{.IncAndGet}}`))
    t.Execute(os.Stdout, c)
    

    Output (try it on the <kbd>Go Playground</kbd>):

    3 4
    

    Note that for this to work, the method needs a pointer receiver (func (c *codec) IncAndGet()) and you have to pass a pointer to Template.Execute() (c is a pointer in our example: c := &codec{Count: 2}).

    If you don't want any result just counting, define it to have a string return type and return the empty string "":

    func (c *codec) Inc() string {
        c.Count++
        return ""
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)