通过删除数组简化模板使用

Simplify template usage by removing array

我正在尝试简化我使用的模板以使其使用更扁平的数据结构:

来自

data := []App{App{"test data", []string{"app1", "app2", "app3"}}}

收件人:

data := App{App{"test data", []string{"app1", "app2", "app3"}}}

即删除 App 的数组,但是当我尝试它时出现错误。

这是工作版本:https://play.golang.org/p/2THGtDvlu01

我尝试将模板更改为

{{ range . -}}
{range $i,$a := .Command}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
{{end}}

但是我收到 type mismatched 错误,知道如何解决吗?

package main

import (
    "log"
    "os"
    "text/template"
)

func main() {
    // Define a template.
    const tmpl = `
echo &1

{{range $i,$a := .Command}}{{if gt $i 0 }} && {{end}}{{.}}{{end}}

echo 2
`

    // Prepare some data
    type App struct {
        Data    string
        Command []string
    }
    data := 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)
    }

}

Playground example

给出输出

echo &1

app1 && app2 && app3

echo 2

Program exited.

如果从代码中删除 []App,则还需要删除模板中使用的 range