为什么程序在不使用template.New()时仍能成功运行?
时间:2024-02-28
浏览:141
作者:佚名
今天golang学习网给大家带来了《为什么程序在不使用template.New()时仍能成功运行?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
我正在尝试使用 html/template 解析结构格式的 json。
func handler(w http.responsewriter, r *http.request) {
var issuelist = template.must(template.new("template01").parsefiles("template01.tmpl"))
result, err := searchissues(os.args[1:])
if err != nil {
log.fatal(err)
}
if err := issuelist.execute(w, result); err != nil {
log.fatal(err)
}
}
函数searchissues用于将流转换为json格式,效果很好。
然后我尝试使用 html/template 解析 json
var issuelist = template.must(template.new("template01").parsefiles("template01.tmpl"))
当我访问本地服务时,出现错误:xxx 是不完整或空的模板。
但是当我删除 new("template01"). 时,程序运行良好。
像这样:
func handler(w http.ResponseWriter, r *http.Request) {
var issueList = template.Must(template.ParseFiles("template01.tmpl"))
result, err := SearchIssues(os.Args[1:])
if err != nil {
log.Fatal(err)
}
if err := issueList.Execute(w, result); err != nil {
log.Fatal(err)
}
}
我不是母语人士,英语不是很好,抱歉。
正确答案
您的第一个代码的问题在于,当您这样做时:
var issuelist = template.must(template.new("template01").
parsefiles("template01.tmpl"))
template.New() 将创建一个名为 "template01" 的新模板。变量 issuelist 将引用此空模板。您调用其 Template.ParseFiles() 方法,该方法将解析 "template01.tmpl" 文件并创建一个名为 "template01.tmpl" 的关联模板。变量 issuelist 仍将引用 template01 模板,而不是从文件中解析的模板。当您调用 Template.Excute() 时,它会执行 issuelist 指定的(默认)模板,即空 template01。这就是您收到错误 incomplete 或空 template 的原因。
在你的第二个版本中:
var issuelist = template.must(template.parsefiles("template01.tmpl"))
您调用 template.ParseFiles()函数,该函数解析 "template01.tmpl" 文件,并返回其模板。因此 issuelist 将引用文件中解析后的模板,而不是空模板。所以 template.execute() 将执行这个模板。
注意:如果在第一种情况下您使用 Template.ExecuteTemplate(),您可以命名要执行的模板:
if err := issueList.Execute(w, "template01.tmpl", result); err != nil {
log.Fatal(err)
}
这将会成功,因为您明确指示执行从文件解析的 "template01.tmpl",而不是默认的空模板。
另请注意,您不应在处理程序中解析模板,这很慢。在此之前解析一次,将结果存储在包级变量中,然后在处理程序中执行它。详情见It takes too much time when using "template" package to generate a dynamic web page to client in Golang
有关关联模板的详细信息,请参阅 Go template name。
另外,请使用 encoding/json 生成 json 输出,而不是 text/template 或 html/template。模板引擎对json格式和编码一无所知,很容易生成无效的json。
今天关于《为什么程序在不使用template.New()时仍能成功运行?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
