小编典典

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

go

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

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}

阅读 806

收藏
2020-07-02

共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"
2020-07-02