首页 > 解决方案 > 通过删除数组来简化模板的使用

问题描述

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

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

标签: templatesgogo-templates

解决方案


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)
    }

}

游乐场示例

给出输出

echo &1

app1 && app2 && app3

echo 2

Program exited.

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


推荐阅读