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

如何在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"
    
    打赏 评论
  • duanfei8399 2018-11-24 19:55

    You give a wrong parameter:

    err = t.Execute(f, t)
    

    It should be

    err = t.Execute(f,[]string{"app1", "app2", "app3"})
    
    打赏 评论
  • douchengchen7959 2018-11-24 19:55

    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.

    打赏 评论

相关推荐 更多相似问题