如何将模板输出写入 Golang 中的文件?

我使用以下代码工作正常,但现在我想将模板打印到文件并尝试以下但出现错误


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}


斯蒂芬大帝
浏览 151回答 3
3回答

慕田峪4524236

使用数组作为第二个参数,而不是模板本身。package mainimport (&nbsp; &nbsp; &nbsp; &nbsp; "html/template"&nbsp; &nbsp; &nbsp; &nbsp; "log"&nbsp; &nbsp; &nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; &nbsp; &nbsp; t := template.Must(template.New("").Parse(`{{- range .}}{{.}}:&nbsp; &nbsp; &nbsp; &nbsp; echo "from {{.}}"{{end}}`))&nbsp; &nbsp; &nbsp; &nbsp; t.Execute(os.Stdout, []string{"app1", "app2", "app3"})&nbsp; &nbsp; &nbsp; &nbsp; f, err := os.Create("./myfile")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("create file: ", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; err = t.Execute(f, []string{"app1", "app2", "app3"})&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Print("execute: ", err)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; f.Close()}输出:app1:&nbsp; &nbsp; echo "from app1"app2:&nbsp; &nbsp; echo "from app2"app3:&nbsp; &nbsp; echo "from app3"而内容myfile是,app1:&nbsp; &nbsp; echo "from app1"app2:&nbsp; &nbsp; echo "from app2"app3:&nbsp; &nbsp; echo "from app3"

PIPIONE

你给了一个错误的参数:err&nbsp;=&nbsp;t.Execute(f,&nbsp;t)它应该是err&nbsp;=&nbsp;t.Execute(f,[]string{"app1",&nbsp;"app2",&nbsp;"app3"})

神不在的星期二

您第二次传递给模板执行的参数应该与您第一次传递的参数相匹配。首先你做:t.Execute(os.Stdout,&nbsp;[]string{"app1",&nbsp;"app2",&nbsp;"app3"})其次你做:err&nbsp;=&nbsp;t.Execute(f,&nbsp;t)您传递了模板本身 (&nbsp;t)。将其更改为:err&nbsp;=&nbsp;t.Execute(f,&nbsp;[]string{"app1",&nbsp;"app2",&nbsp;"app3"})您的模板迭代传递的参数(带有一个{{range}}动作),当您传递一个切片时它会起作用,而在传递模板时它不会起作用,它是一个指向结构的指针,它不是模板引擎可以迭代的东西。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go