admin管理员组文章数量:1345391
What I'm trying to achieve is using r.LoadHTMLGlob("./web/templates/**/*")
and loading pages "dynamically". Both Go and Gin are very new to me, so I'm not sure what I'm doing is hacky/incorrect, or if it's even possible and I'm misguided.
In /web:
/web/main.go
import (
"log"
"net/http"
"github/gin-gonic/gin"
)
func Start(port int) *http.Server {
r := gin.Default()
svrWeb := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: r,
}
r.LoadHTMLGlob("./web/templates/**/*")
r.Static("/static", "./web/static")
r.GET("/", Home)
r.GET("/user", User)
go func() {
if err := svrWeb.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("// ERROR: Failed to start API server: %v", err)
}
}()
return svrWeb
}
/web/home.go
import (
"net/http"
"github/gin-gonic/gin"
)
func Home(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "Home",
"content": "home",
})
}
/web/user.go
import (
"net/http"
"github/gin-gonic/gin"
)
func User(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "User",
"content": "user",
})
}
/web/templates/layout/base.html
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .title }}</title>
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="/static/css/buttons.css">
<link rel="stylesheet" href="/static/css/dashboard.css">
<link rel="preconnect" href=";>
<link rel="preconnect" href="; crossorigin>
<link href="+Sans&family=IBM+Plex+Sans:ital,wght@0,100..700;1,100..700&display=swap" rel="stylesheet">
<link href='/[email protected]/css/boxicons.min.css' rel='stylesheet'>
</head>
<body>
{{ template "head" . }}
{{ template "content" . }}
{{ template "foot" . }}
</body>
</html>
{{ end }}
/web/templates/pages/home.html
{{ define "content" }}
You are Home
{{ end }}
/web/templates/pages/user.html
{{ define "content" }}
You are User
{{ end }}
When I load / I get "You are Home". But when I load /user, I still get "You are Home". If I change {{ template "content" . }}
to {{ .content }}
, I get the single text from "content": "home",
in the respective function.
Thanks
What I'm trying to achieve is using r.LoadHTMLGlob("./web/templates/**/*")
and loading pages "dynamically". Both Go and Gin are very new to me, so I'm not sure what I'm doing is hacky/incorrect, or if it's even possible and I'm misguided.
In /web:
/web/main.go
import (
"log"
"net/http"
"github/gin-gonic/gin"
)
func Start(port int) *http.Server {
r := gin.Default()
svrWeb := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: r,
}
r.LoadHTMLGlob("./web/templates/**/*")
r.Static("/static", "./web/static")
r.GET("/", Home)
r.GET("/user", User)
go func() {
if err := svrWeb.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("// ERROR: Failed to start API server: %v", err)
}
}()
return svrWeb
}
/web/home.go
import (
"net/http"
"github/gin-gonic/gin"
)
func Home(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "Home",
"content": "home",
})
}
/web/user.go
import (
"net/http"
"github/gin-gonic/gin"
)
func User(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "User",
"content": "user",
})
}
/web/templates/layout/base.html
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .title }}</title>
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="/static/css/buttons.css">
<link rel="stylesheet" href="/static/css/dashboard.css">
<link rel="preconnect" href="https://fonts.googleapis">
<link rel="preconnect" href="https://fonts.gstatic" crossorigin>
<link href="https://fonts.googleapis/css2?family=Odibee+Sans&family=IBM+Plex+Sans:ital,wght@0,100..700;1,100..700&display=swap" rel="stylesheet">
<link href='https://unpkg/[email protected]/css/boxicons.min.css' rel='stylesheet'>
</head>
<body>
{{ template "head" . }}
{{ template "content" . }}
{{ template "foot" . }}
</body>
</html>
{{ end }}
/web/templates/pages/home.html
{{ define "content" }}
You are Home
{{ end }}
/web/templates/pages/user.html
{{ define "content" }}
You are User
{{ end }}
When I load / I get "You are Home". But when I load /user, I still get "You are Home". If I change {{ template "content" . }}
to {{ .content }}
, I get the single text from "content": "home",
in the respective function.
Thanks
Share Improve this question edited 2 days ago Justin asked 2 days ago JustinJustin 14311 bronze badges2 Answers
Reset to default 0I think there are libraries that will help with this, but I am not sure, so you might want to check the Gin contribs. If you want to do this yourself, there are ways. Below is one way of doing it:
The key is that the order in which templates are defined matters. So if you have a base template:
base.tmpl:
..header..
{{template "content" .}}
..footer..
{{define "content"}}{{end}}
You define the layout, and the placeholder templates, like the content
template above. If you parse this template file, the content
will be empty.
Then you define different contents:
content1.tmpl:
{{define "content"}}
content 1
{{end}}
content2.html
{{define "content"}}
content 2
{{end}}
Then, you instantiate these templates:
content1,err:=template.ParseFiles("base.tmpl","content1.tmpl")
content2,err:=template.ParseFiles("base.tmpl","content2.tmpl")
When you run content1
, you will get the content1.html
contents embedded in the base. When you run content2
, you will get the content2.html
contents embedded in the base.
You can also direct this parsing with some sort of a manifest file where you list the template bits building a composite template.
There is an example of it here: https://github/PacktPublishing/Go-Recipes-for-Developers/blob/main/src/chp2/template-layout/main.go
{{ template "content" . }}
The problem lies in the template lookup mechanism.
When the Go template engine looks up templates, it returns the first matching template definition based on the loading order. Since you loaded both home.html
and user.html
, which both define the content
section, Go will only use the first definition it finds.
You need to use different names for the content
template of each page, for example:
<!-- templates/pages/home.html -->
{{ define "home-content" }}
You are Home
{{ end }}
<!-- templates/pages/user.html -->
{{ define "user-content" }}
You are User
{{ end }}
Then, in the controller, specify which content
template to use specifically.
package main
import (
"bytes"
"fmt"
"html/template"
"net/http"
"github/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.SetFuncMap(template.FuncMap{
"DynamicTemplate": func(name string, data interface{}) template.HTML {
buf := new(bytes.Buffer)
tmpl := template.Must(template.New("").ParseGlob("templates/pages/*.html"))
err := tmpl.ExecuteTemplate(buf, name, data)
if err != nil {
return template.HTML(fmt.Sprintf("Error: template %s not found", name))
}
return template.HTML(buf.String())
},
})
r.LoadHTMLGlob("templates/**/*")
r.GET("/", Home)
r.GET("/user", User)
r.Run(":8080")
}
func Home(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "Home",
"content": "home-content",
})
}
func User(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"title": "User",
"content": "user-content",
})
}
<!-- templates/layout/base.html -->
{{ define "base" }}
<!DOCTYPE html>
<html>
<head>
<title>{{ .title }}</title>
</head>
<body>
{{ DynamicTemplate .content . }}
</body>
</html>
{{ end }}
本文标签: go ginUsing Go Gin with nested template filesStack Overflow
版权声明:本文标题:go gin - Using Go Gin with nested template files - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743808901a2542695.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论