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

问题描述 投票:1回答:1

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

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的错误,任何想法如何解决它?

templates go go-templates
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.