templates - 如何更新 Go 模板中的字段值

标签 templates go struct

我有以下情况,我将包含映射的结构传递给模板:

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)
    }
}

我想增加 codecCount 字段,这样我就可以知道我看到了多少个 map 项。

最佳答案

一个解决方案是使 plus1 函数成为一个直接作用于 codec 值的闭包:

// first create a codec instance
c := codec {a, 0}

// now define the function as a closure with a reference to c
fns := template.FuncMap{
  "plus1": func() int {
      c.Count++
      return c.Count
   },
}

// now we don't need to pass anything to it in the template
t := template.Must(template.New("abc").Funcs(fns).Parse(`{{$l := len .Names}}{{range $k, $v := .Names}}{{if ne (plus1) $l}}{{$k}} {{$v}} {{end}}{{end}}.`))

输出是:

one 1 three 3

我猜你的目标是什么?并在执行结束时将该值保留在c中。

关于templates - 如何更新 Go 模板中的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35034039/

相关文章:

c++ - 使用类名的模板值作为指针

go - GC是否处理数组的未指向部分

c++ - 无法标记字符串并将其传递给 C++ 中的结构

c++ - 将字符缓冲区转换为结构

c++ - C++ 中的部分模板函数规范有效,但为什么呢?

c++模板到模板参数

c++ - 返回奇数的简单简单模板?

google-app-engine - 将 Hugo 站点部署到 GAE 结果为 "internal error 13"

c++ - Go 共享库作为 C++ 插件

c - 用文件中的数据填充结构