dsg56465 2018-11-24 19:50
浏览 712
已采纳

如何在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()
}

The error is:

execute: template: :1:10: executing "" at <.>: range can't iterate over {0xc00000e520 0xc00001e400 0xc0000b3000 0xc00009e0a2}
  • 写回答

3条回答 默认 最新

  • duanfengtuo6012 2018-11-24 20:03
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算