gpt4 book ai didi

go - 在模板中使用函数而不是方法

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:40 25 4
gpt4 key购买 nike

我使用下面的代码

var data struct {
File FZR
API API
}


const tmpl = `
{{- range .File.Modules}}
# in context of {{.Name}}

echo {{.EchoText}}
{{end}}`

func EchoText(m mts) string {
return m.Type
}

这样不行,现在我把它改成

func (m mts) EchoText() string {
return m.Type
}

它会工作,但我想让它与第一个选项一起工作,我该怎么做?我的意思是更新模板...

更新:作为批准答案https://golang.org/pkg/text/template/#example_Template_func

但是只有字符串,如何注册EchoText

最佳答案

正如@mkopriva 在他的第一条评论中建议的那样,您只需将所有函数引用到 template.FuncMap 中,您可以在其中建立从名称到函数的映射

然后进入模板,您只需调用它们并将 mts 作为参数传递给它们。

package main

import (
"log"
"os"
"text/template"
)

type mts struct {
Type1 string
Type2 string
}

func main() {
funcMap := template.FuncMap{
"myFunc1": EchoType1,
"myFunc2": EchoType2,
}

const templateText = `
Input: {{printf "%q" .}}
Output1:{{myFunc1 .}}
Output2:{{myFunc2 .}}
`

tmpl, err := template.New("myFuncTest").Funcs(funcMap).Parse(templateText)
if err != nil {
log.Fatalf("parsing: %s", err)
}

myMts := mts{Type1: "myType1", Type2: "myType2"}
err = tmpl.Execute(os.Stdout, myMts)
if err != nil {
log.Fatalf("execution: %s", err)
}
}

func EchoType1(m mts) string {
return m.Type1
}

func EchoType2(m mts) string {
return m.Type2
}

这将产生以下输出:

Input: {"myType1" "myType2"}

Output1:myType1

Output2:myType2

关于go - 在模板中使用函数而不是方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50115229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com