Golang中如何设置html/template的路径
Golang中如何设置html/template的路径 大家好, 我尝试将我的代码连接到HTML视图。 以下是我尝试连接到HTML的方式: https://play.golang.org/p/PCv74Rxupj3
但我遇到了这个错误:
panic: html/template: pattern matches no files: view/*.gohtml
goroutine 1 [running]: html/template.Must(…) /home/mehrdad/workspace/go/go/src/html/template/template.go:372 github.com/mehrdaddolatkhah/cafekala_server/pkg/business/web.init.0() /home/mehrdad/workspace/go/projects/src/mehrdaddolatkhah/cafekala_back/pkg/business/web/AuthWebHandler.go:26 +0x96 exit status 2
这是我的项目结构: -cmd -pkg – business —web ----AuthWebHandler.go –domain –repository –transport –view —login.gohtml
可以请教一下如何修复这个问题吗?
更多关于Golang中如何设置html/template的路径的实战教程也可以访问 https://www.itying.com/category-94-b0.html
感谢您的回复。
由于我是从架构中的路由部分调用此函数,所以现在我不知道该如何为 login.gohtml 指定路径。
我在本主题的第一个帖子中分享了包结构。
更多关于Golang中如何设置html/template的路径的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
有点跑题了
但 w.Write([]byte(fmt.Sprintf("enter phone and password"))) 在我看来有点复杂。
为什么不直接这样做:
fmt.Fprint(w, "enter phone and password")
在你的代码中,template.Must() 函数尝试从 view/*.gohtml 路径加载模板文件,但根据你的项目结构,模板文件位于 pkg/view/ 目录下,而不是相对于 AuthWebHandler.go 的 view/ 目录。
你需要调整模板路径以正确指向模板文件的位置。以下是修复方案:
package web
import (
"html/template"
"path/filepath"
"runtime"
)
var (
// 获取当前文件的目录
_, b, _, _ = runtime.Caller(0)
basePath = filepath.Dir(b)
)
// 使用绝对路径加载模板
var templates = template.Must(template.ParseGlob(filepath.Join(basePath, "../view/*.gohtml")))
或者,如果你知道项目的根目录结构,可以使用相对路径:
package web
import (
"html/template"
"path/filepath"
)
// 从项目根目录开始指定路径
var templates = template.Must(template.ParseGlob(filepath.Join("pkg", "view", "*.gohtml")))
如果你使用的是 Go Modules,并且模板文件位于模块根目录下的 view/ 文件夹中:
package web
import (
"html/template"
)
// 假设模板文件在项目根目录的 view 文件夹中
var templates = template.Must(template.ParseGlob("view/*.gohtml"))
根据你的实际项目结构,选择适合的路径配置。确保 ParseGlob 的路径模式能正确匹配到你的 .gohtml 文件位置。


