【发布时间】:2018-08-31 17:10:27
【问题描述】:
我需要从文本模板键值中返回,就像下面的注释和命令
#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 作为参考。
【问题讨论】:
-
如果每次调用都需要
--type选项,您可以考虑改用子命令:extract format --format=json或extract order --format=xml -
是的,我就是这个意思
-
在
TypeCommand为什么要返回 String 并提到返回类型为 Dependency ? -
@TarunLalwani - 不,这是错误的,我需要返回键值才能从模板中打印出来,知道怎么做吗?
-
如果你的
Commandstruct 和Commandstruct 字段被命名为不同的东西会很有帮助。
标签: go