Golang - 文本/模板返回键值

14 go

我需要返回文本模板键值,这将像注释和命令,如下所示

 #Description for npm install 
   npm install
 #Description for test
   npm test
 #Description for test2 
   run test2
Run Code Online (Sandbox Code Playgroud)

为此,我创建了如下函数:

// 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"
}
Run Code Online (Sandbox Code Playgroud)

模板是:

const tmpl = `
{{- range .File.Dependency}}

{{.TypeCommand}}
{{end}}`

type Command struct {
    Info    string
    Command string
}
Run Code Online (Sandbox Code Playgroud)

当我将模板更改为以下内容时,出现错误:

const tmpl = `
    {{- range .File.Dependency}}

     {{  TypeCommand .}}
   {{ range .Command}}
    {{ .Info }}
    {{ .Command }}
   {{end}}
  {{end}}
        '
Run Code Online (Sandbox Code Playgroud)

executing "tmpl3.txt" at <.Command>: can't evaluate field Command in type *Dependency

我用这个作为参考.

Ven*_*ius 4

您收到的错误消息是因为您只是丢弃了返回值,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"}}
}
Run Code Online (Sandbox Code Playgroud)

现在我们返回多个命令,我们可以在模板中对它们进行范围调整,它们将被自动绑定。我将您的模板稍微调整为以下内容:

const tmpl = `
{{- range .File.Dependency}}
  {{- range .TypeCommand }}
{{ .Info}}
  {{ .Command}}
{{- end}}{{end}}`
Run Code Online (Sandbox Code Playgroud)

当我在 Go Playground 中运行此命令时,得到了以下输出,这似乎正是您想要的:

#Description for npm install
  npm install
#Description for test
  npm test
#Description for test2
  run test2
#test 2
  foo
Run Code Online (Sandbox Code Playgroud)