我使用下面的代码可以正常工作,但是现在我想将模板打印到文件中,并尝试以下操作,但出现错误
package main
import (
"html/template"
"log"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range .}}{{.}}:
echo "from {{.}}"
{{end}}
`))
t.Execute(os.Stdout, []string{"app1", "app2", "app3"})
f, err := os.Create("./myfile")
if err != nil {
log.Println("create file: ", err)
return
}
err = t.Execute(f, t)
if err != nil {
log.Print("execute: ", err)
return
}
f.Close()
}
错误是:
execute: template: :1:10: executing "" at <.>: range can't iterate over {0xc00000e520 0xc00001e400 0xc0000b3000 0xc00009e0a2}
答案 0 :(得分:0)
您输入了错误的参数:
err = t.Execute(f, t)
应该是
err = t.Execute(f,[]string{"app1", "app2", "app3"})
答案 1 :(得分:0)
您第二次传递给模板执行的参数应与您第一次传递的参数匹配。
首先,您要做的是:
t.Execute(os.Stdout, []string{"app1", "app2", "app3"})
第二步:
err = t.Execute(f, t)
您通过了模板本身(t
)。更改为:
err = t.Execute(f, []string{"app1", "app2", "app3"})
您的模板遍历传递的参数(使用{{range}}
操作),该参数在您传递切片时有效,而在传递模板时则无效,它是指向结构的指针,不是模板引擎可以迭代。
答案 2 :(得分:-1)
使用数组作为第二个参数,而不是模板本身。
package main
import (
"html/template"
"log"
"os"
)
func main() {
t := template.Must(template.New("").Parse(`{{- range .}}{{.}}:
echo "from {{.}}"
{{end}}
`))
t.Execute(os.Stdout, []string{"app1", "app2", "app3"})
f, err := os.Create("./myfile")
if err != nil {
log.Println("create file: ", err)
return
}
err = t.Execute(f, []string{"app1", "app2", "app3"})
if err != nil {
log.Print("execute: ", err)
return
}
f.Close()
}
输出:
app1:
echo "from app1"
app2:
echo "from app2"
app3:
echo "from app3"
myfile
的内容是
app1:
echo "from app1"
app2:
echo "from app2"
app3:
echo "from app3"