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

标签 templates go go-templates

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

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}

最佳答案

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

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"

关于templates - 如何将模板输出写入 Golang 中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461812/

相关文章:

go - 接口(interface)转换 : interface {} is uint64, 不是 float32

go - 使用用户名或电子邮件地址登录

templates - 文本模板不适用于某些单词

go - 在Helm模板中解压Go map 值

templates - Azure DevOps 管道 : same template twice in one stage

c++ - 显式模板特化

c++ - 局部变量的引用崩溃

javascript - webRTC - 多房间视频 session

templates - 在Go模板中按名称访问结构成员

c++ - 模板和常量类型?