如何在Golang中将模板输出写入文件? [英] How to write template output to a file in Golang?

查看:57
本文介绍了如何在Golang中将模板输出写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the following code which work ok, but now I want to print the template to a file and tried the following but got error

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}

推荐答案

使用数组作为第二个参数,而不是模板本身.

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

输出:

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"

这篇关于如何在Golang中将模板输出写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆