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

时间:2018-08-29 17:18:34

标签: templates go go-templates

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

来自

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错误,知道如何解决吗?

1 个答案:

答案 0 :(得分:1)

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

相关问题