登录
首页 >  Golang >  Go问答

template.Execute 无数据传递

来源:stackoverflow

时间:2024-03-20 23:57:32 310浏览 收藏

在使用 `text/template` 时遇到 `Execute` 未传递数据的错误。尽管遵循了示例,但输出中并未发生模板扩展,导致 `index.gohtml` 中的 `sages` 名称无法插入到 HTML 中。

问题内容

我做了与讲座相同的事情。 但输出中没有发生模板扩展,而我希望看到 sages 中的名称被插入到输出 html 中。

package main

import (
    "log"
    "os"
    "text/template"
)

var tpl *template.template

func init() {
    tpl = template.must(template.parsefiles("index.gohtml"))
}

func main() {
    sages := []string{"mlk", "jesus", "buddha"}
    err := tpl.execute(os.stdout, sages)
    if err != nil {
        log.fatal(err)
    }
}

index.gohtml如下:




    
    The HTML5 Herald


    {{range .}}
  • {{.}}
  • {{end}}

可以在此处查看输出。


解决方案


您正在使用 text/template,而您应该使用 html/template,但这不会导致问题。

很难从图像中重现,但考虑到双倍行距的输出,我猜你的模板文件已保存为 utf-16,而 go 需要 utf-8。鉴于您的输入文件仅包含来自低编号 unicode 代码点的字符,这将导致 0 字节和输入中的实际字节交替出现。

到这里,我们也就讲完了《template.Execute 无数据传递》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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