我需要返回文本模板键值,就像下面的注释和命令
#Description for npm install
npm install
#Description for test
npm test
#Description for test2
run test2
为此,我创建了如下函数:
// example with switch
func (d Dependency) TypeCommand() Command {
switch d.Type {
case "runner":
cmd1 := Command{"#Description for npm install", "npm install"}
cmd2 := Command{"#Description for test", "npm test"}
cmd3 := Command{"#Description for test2", "run test2"}
case "runner2":
return "test 2"
}
return "command_baz"
}
模板是:
const tmpl = `
{{- range .File.Dependency}}
{{.TypeCommand}}
{{end}}`
type Command struct {
Info string
Command string
}
当我将模板更改为以下内容时,出现错误:
const tmpl = `
{{- range .File.Dependency}}
{{ TypeCommand .}}
{{ range .Command}}
{{ .Info }}
{{ .Command }}
{{end}}
{{end}}
'
executing "tmpl3.txt" at <.Command>: can't evaluate field Command in type *Dependency
我使用 this作为引用。
最佳答案
您收到的错误消息是因为您只是丢弃了 TypeCommand
的返回值,而不是将其传递到您尝试访问其结构字段的位置。我们可以解决这个问题,但这可能不是您想要做的,因为您的 TypeCommand
函数看起来应该返回多个命令而不是单个命令。所以让我们先重写一下:
func (d Dependency) TypeCommand() []Command {
switch d.Type {
case "runner":
return []Command{
Command{"#Description for npm install", "npm install"},
Command{"#Description for test", "npm test"},
Command{"#Description for test2", "run test2"},
}
case "runner2":
return []Command{Command{"#test 2", "foo"}}
}
return []Command{Command{"#command_baz", "baz"}}
}
现在我们返回了多个命令,我们可以在模板中对它们进行范围覆盖,它们将被自动绑定(bind)。我将您的模板稍微调整为以下内容:
const tmpl = `
{{- range .File.Dependency}}
{{- range .TypeCommand }}
{{ .Info}}
{{ .Command}}
{{- end}}{{end}}`
当我在 Go Playground 中运行它时,我得到了以下输出,这似乎是你想要的:
#Description for npm install
npm install
#Description for test
npm test
#Description for test2
run test2
#test 2
foo
关于Golang - 文本/模板返回键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49425690/