How to write template output to a file in Golang?

ⅰ亾dé卋堺 提交于 2019-12-06 09:36:37
Shudipta Sharma

Use the array as the second argument, not the template itself.

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()
}

Output:

app1:
    echo "from app1"
app2:
    echo "from app2"
app3:
    echo "from app3"

And the content of myfile is,

app1:
    echo "from app1"
app2:
    echo "from app2"
app3:
    echo "from app3"

The parameter you pass to the template execution the second time should match what you pass for the first time.

First you do:

t.Execute(os.Stdout, []string{"app1", "app2", "app3"})

Second you do:

err = t.Execute(f, t)

You passed the template itself (t). Change it to:

err = t.Execute(f, []string{"app1", "app2", "app3"})

Your template iterates over the passed param (with a {{range}} action) which works when you pass a slice, and it won't work when passing the template, it's a pointer to a struct, it's not something the template engine could iterate over.

Stéphane Jeandeaux

You give a wrong parameter:

err = t.Execute(f, t)

It should be

err = t.Execute(f,[]string{"app1", "app2", "app3"})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!