我在golang上有两个网页,我想将此页面代码嵌入到{{.content}}变量(在templates / main.html中定义)中,并根据即将到来的请求动态添加。
例如,如果访客进入我想要的{{.content}}变量的用户注册页面,将是用户注册代码,否则是用户配置文件代码。
templates / userregister.html页面代码;
{{ define "userregister" }}
...
{{.specialmessage}}
...
{{ end }}
templates / userprofile.html页面代码;
{{ define "userprofile" }}
...
{{.specialmessage}}
...
{{ end }}
templates / main.html;
{{ define "main" }}
<!DOCTYPE html>
<html lang="tr">
{{ template "head" . }}
<body>
<div class="container-fluid">
{{ template "header" . }}
<div class="row">
<nav class="col-12 col-md-2 p-0">
{{ template "leftmenu" . }}
</nav>
<div class="container-fluid col-12 col-md-10">
{{.content}}
</div>
</div>
{{ template "footer" . }}
</div>
</body>
</html>
{{ end }}
用户注册页面控制器;
func PgUserRegister(c *gin.Context) {
c.HTML(http.StatusOK,"main", gin.H{
"pgETitle": "User Register page",
"specialmessage": "You are on the userregister page.",
"content": template.ParseFiles("userregister.html"),
})
}
用户个人资料页面控制器;
func PgUserProfile(c *gin.Context) {
c.HTML(http.StatusOK,"main", gin.H{
"pgETitle": "User Profile",
"specialmessage": "You are on the userprofile page.",
"content": template.ParseFiles("userprofile.html"),
})
}
答案 0 :(得分:1)
启动路由器时解析所有模板。
router.LoadHTMLFiles("templates/main.html", "templates/userregister.html", "templates/userprofile.html")
然后在处理程序中向gin.H{ ... }
表达式中添加一个布尔变量,例如"isLoggedIn"
,然后在主模板中使用if-else
action和template
操作。
{{ if .isLoggedIn }}
{{ template "userprofile" . }}
{{ else }}
{{ template "userregister" . }}
{{ end }}