代码之家  ›  专栏  ›  技术社区  ›  07_05_GuyT

golang模板从字符串数组错误生成值

  •  0
  • 07_05_GuyT  · 技术社区  · 7 年前

    我正在使用Golang项目,需要生成以下内容

    app1 && app2 && app3

    我的模板如下

    {{- range ExeApp .}} {{ .Command }} {{- end}}
    

    我的代码看起来像下面的命令,它是字符串数组

    type App struct {
       Data    string
       Command []string
    }
    
    //This is the function
    func ExeApp(m models) []App {
    
       switch m.Type {
       case “apps":
          return []App{
             {"# running apps",
                []string{“app1", “app2", “app3"}},
          }
    
    …
    

    目前它的生成方式

    [app1 app2 app3]
    

    我需要它就像

    应用程序1和应用程序2和应用程序3 ,

    我尝试在.command之前添加&&&命令,这对我没有帮助,此外,我不知道如何在应用程序之前和之后删除数组[],知道我在这里做了什么错误吗?

    我试过以下方法

    {{- range .ExeApp}} {{range .Command }} && {{.}} {{end}} {{- end}}
    

    但现在我被甩了 错误: unexpected EOF 未定义“命令”功能

    运行模板时

    要生成的代码是:

    funcMap := template.FuncMap{
        "ExeApp": ExeApp,
    }
    t, err := template.New("file.txt").Funcs(funcMap).ParseFiles(container)
    

    如果我使用第一个结构(同样的结构,没有字符串数组,当然也适应了对象的代码),一切都按预期工作。

    也可以试试这个 {{-range .ExeApp}} {{range .Command}} {{.}} {{end}} {{end}}

    现在我出错了

    executing "file.txt" at <.ExeApp>: can't evaluate field ExeApp in type *models
    

    为什么:

    1 回复  |  直到 7 年前
        1
  •  1
  •   Kenny Grant JimB    7 年前

    https://play.golang.org/p/O8rpum8LtZr

    // Define a template.
    const tmpl = `
    {{ range . -}}
    {{range $i,$a := .Command}}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
    {{end}}
    `
    
    // Prepare some data
    type App struct {
        Data    string
        Command []string
    }
    data := []App{App{"test data", []string{"app1", "app2", "app3"}}}
    
    // Create a new template and parse into it.
    t := template.Must(template.New("tmpl").Parse(tmpl))
    
    // Execute the template with data
    err := t.Execute(os.Stdout, data)
    if err != nil {
        log.Println("executing template:", err)
    }
    

    docs

    os/exec

    {{ range ExeApp }}

    https://play.golang.org/p/euWxctWRbp_L