golang中没有这样的文件或目录错误
发布时间:2020-12-16 09:24:46 所属栏目:大数据 来源:网络整理
导读:我想在我的一个golang控制器中指定一个html模板 我的目录结构是这样的 Project -com -src - controller -contoller.go -view - html -first.html 我想加载first.html for request / new.我已经将NewHandler用于url / new,而NewHandler func正在执行/ new请求
我想在我的一个golang控制器中指定一个html模板
我的目录结构是这样的 Project -com -src - controller -contoller.go -view - html -first.html 我想加载first.html for request / new.我已经将NewHandler用于url / new,而NewHandler func正在执行/ new请求并且在controller.go中.这是我的代码 func NewHandler(w http.ResponseWriter,r *http.Request) { t,err := template.ParseFiles("view/html/first.html") if err == nil { log.Println("Template parsed successfully....") } err := templates.ExecuteTemplate(w,"view/html/first.html",nil) if err != nil { log.Println("Not Found template") } // t.Execute(w,"") } 但是我收到了一个错误 panic: open first.html: no such file or directory 请帮我删除此错误.提前致谢 解决方法
我通过给出html的绝对路径解决了这个问题.为此,我创建了一个解析html的类
package htmltemplates import ( "html/template" "path/filepath" ) 在我删除的NewHandler方法中 func init() { filePrefix,_ := filepath.Abs("./work/src/Project/view/html/") // path from the working directory Templates = template.Must(template.ParseFiles(filePrefix + "/first.html")) ... //htmls must be specified here to parse it } 在NewHandler中,我删除了前5行而是给了 err := htmltemplates.Templates.ExecuteTemplate(w,"first.html",nil) 它现在正在工作.但如果有的话,需要一个更好的解决方案 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |