登录
首页 >  Golang >  Go问答

template:一个缺乏内容的模板

来源:stackoverflow

时间:2024-03-04 12:00:28 223浏览 收藏

你在学习Golang相关的知识吗?本文《template:一个缺乏内容的模板》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有以下一段代码,我尝试使用 gopkg.in/gomail.v2 发送电子邮件。当电子邮件模板像这样放置在项目的根目录中时,我完全能够发送电子邮件

./
    main.go
    template.html
// Info defines
type Info struct {
    Age  int
    Name string
}

func (i Info) sendMail() {
    fp := filepath.Join("template.html")

    t := template.New(fp)

    var err error
    t, err = t.ParseFiles(fp)
    if err != nil {
        log.Println(err)
    }

    var tpl bytes.Buffer
    if err := t.Execute(&tpl, i); err != nil {
        log.Println(err)
    }

    result := tpl.String()
    // ... email sending logic
}

func main() {
    info := &Info{
        Name: "name 1",
        Age:  20,
    }

    info.sendMail()
}

但是当我将模板目录更改为 emails/template.html 并将文件路径更改为

fp := filepath.join("emails", "template.html")

然后我从 t.execute() 收到错误

template:“emails/template.html”是不完整或空的模板

我也尝试过 fp, _ := filepath.abs​​("emails/template.html") 弯弯弯弯 但出现错误

template:“/mnt/data/go/test/emails/template.html”是不完整或空模板 不过提到的路径是正确的。


解决方案


我变了

if err := t.execute(&tpl, i); err != nil {
        log.println(err)
    }

if err := t2.ExecuteTemplate(&tpl, "template.html", i); err != nil {
        log.Println(err)
    }

成功了

如果我想使用 t.execute(&tpl, i) 代替,那么我必须在创建模板时将模板名称指定为文件名

t := template.new("template.html")

今天关于《template:一个缺乏内容的模板》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>