我想在我的一个 golang 控制器中指定一个 html 模板我的目录结构是这样的
Project
-com
-src
- controller
-contoller.go
-view
- html
-first.html
Run Code Online (Sandbox Code Playgroud)
我想为请求 /new 加载 first.html。我已经将 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, "")
}
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误
panic: open first.html: no such file or directory
Run Code Online (Sandbox Code Playgroud)
请帮我消除这个错误。提前致谢
我已经通过提供 html 的绝对路径解决了这个问题。为此,我创建了一个在其中解析 html 的类
package htmltemplates
import (
"html/template"
"path/filepath"
)
Run Code Online (Sandbox Code Playgroud)
在我删除的 NewHandler 方法中 //Templates 用于存储所有模板 var Templates *template.Template
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
}
Run Code Online (Sandbox Code Playgroud)
在 NewHandler 中,我删除了前 5 行,而是给出了
err := htmltemplates.Templates.ExecuteTemplate(w, "first.html", nil)
Run Code Online (Sandbox Code Playgroud)
它现在正在工作。但是如果有的话需要更好的解决方案
| 归档时间: |
|
| 查看次数: |
14482 次 |
| 最近记录: |