Golang - 文本/模板返回键值

标签 go

我需要返回文本模板键值,就像下面的注释和命令

 #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/

相关文章:

转到/pkg/工具/linux_amd64/链接 : running gcc failed: exit status 1/usr/bin/ld: cannot find -lgdal

go - 无法在 mac os 中安装 gRPC for go

go - 在Golang中发布Slackbot响应

go - 无法在 eclipse che 中运行 delve - 无法启动进程,不允许操作

json - 结果打印空 Json

python - 无法让 python 跟随 base32 编码

google-app-engine - martini & appengine/golang,返回 memcached JSON 数据

go - 如何测试二进制字符串是否有效的UTF8?

go - 使用外包文件中的函数

mongodb - 在文档 mongodb mgo 驱动程序中增加嵌套数组的特定值