Templates 通过删除阵列简化模板使用
我试图简化模板,使其使用更平坦的数据结构: 从 致: i、 e.删除Templates 通过删除阵列简化模板使用,templates,go,go-templates,Templates,Go,Go Templates,我试图简化模板,使其使用更平坦的数据结构: 从 致: i、 e.删除应用程序的数组,但是当我尝试它时,我得到一个错误 以下是工作版本: 我试图将模板更改为 {{ range . -}} {range $i,$a := .Command}{{if gt $i 0 }} && {{end}}{{.}}{{end}} {{end}} 但是我得到了一个类型不匹配的错误,你知道怎么修复吗 package main import ( "log" "os" "tex
应用程序的数组
,但是当我尝试它时,我得到一个错误
以下是工作版本:
我试图将模板更改为
{{ range . -}}
{range $i,$a := .Command}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
{{end}}
但是我得到了一个类型不匹配的错误,你知道怎么修复吗
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.
如果从代码中删除[]应用程序
,还需要删除模板中使用的范围
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.