我有一个Gin Web应用程序,基于一组分词和一个基本模板的多个HTML模板.基本模板似乎与相关的部分一起呈现得很好,但我的主视图、登录、索引和注册并没有像预期的那样呈现.每当我访问其中任何一个的HTTP端点时,只有注册视图呈现.
以下文件中缺少什么或配置错误,导致我的路由无法呈现所请求的页面?
我的项目有以下 struct .
├── app
...
│ ├── handlers
│ │ ├── general
│ │ │ └── general.go
│ │ └── routes.go
│ ├── main.go
│ ├── reloadDev.sh
│ ├── static
│ │ ├── css
│ │ ├── img
│ │ └── js
│ └── templates
│ ├── home
│ │ ├── index.tmpl.html
│ │ ├── login.tmpl.html
│ │ └── 注册.tmpl.html
│ ├── layouts
│ │ └── Bas.tmpl.嗯!
│ └── partials
│ ├── footer.tmpl.html
│ ├── head.tmpl.html
│ └── navbar.tmpl.html
Bas.tmpl.嗯!
{{ define "base" }}
<!DOCTYPE html>
<html lang="eng" data-bs-theme="dark">
{{ template "head" . }}
{{template "navbar" .}}
<body>
{{ block "content" . }}{{ end }}
</body>
{{template "footer" .}}
</html>
{{end}}
注册.tmpl.html
{{ template "base" . }}
{{ define "content" }}
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h1>Register</h1>
<form action="/register" method="post">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
</div>
...SNIP...
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
{{ end }}
Index.tmpl.html(Login的 struct 与这两者相同.)
{{ template "base" . }}
{{ define "title" }}Home{{ end }}
{{ define "content" }}
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<p>Welcome to Astra Porta.</p>
<p>Click <a href="/login">here</a> to login.</p>
</div>
</div>
</div>
{{ end }}
使用embed.FS
将HTML模板与二进制文件Bundle 在一起.
//go:embed templates/partials/* templates/layouts/* templates/home/*
var files embed.FS
func main() {
router := setupRouter()
err := router.Run()
if err != nil {
panic(err)
}
}
func setupRouter() *gin.Engine {
router := gin.Default()
subFS, e := fs.Sub(files, "templates")
if e != nil {
panic(e)
}
tmpl := template.Must(template.ParseFS(
subFS,
"layouts/*.html",
"partials/*.html",
"home/*.html",
))
router.SetHTMLTemplate(tmpl)
router.StaticFS("/static", http.Dir("static"))
err := router.SetTrustedProxies(nil)
if err != nil {
panic(err)
}
handlers.InitializeRoutes(&router.RouterGroup)
return router
}
并且页面在我的应用程序路径内呈现.这里的引用映射到这*.tmpl.html
个文件的文件名.
func SiteIndex(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl.html", nil)
}
func GetRegister(c *gin.Context) {
c.HTML(http.StatusOK, "注册.tmpl.html", nil)
}
func GetLogin(c *gin.Context) {
c.HTML(http.StatusOK, "login.tmpl.html", nil)
}