如何将web模板变量设置为动态html和golang代码?

问题描述 投票:0回答:1

我在golang上有两个网页,我希望将这些页面代码嵌入{{.content}}变量(在templates / main.html中定义),根据即将到来的请求进行动态处理。

例如,如果guest虚拟机进入userregister页面,我希望{{.content}}变量将是userregister代码,否则将是userprofile代码。

templates / userregister.html页面代码;

{{ define "userregister" }}
   ...
   {{.specialmessage}}
   ...
{{ end }}

templates / userprofile.html页面代码;

{{ define "userprofile" }}
   ...
   {{.specialmessage}}
   ...
{{ end }}

模板/ 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 }}

userregister页面控制器;

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"),
    })
}

userprofile页面控制器;

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"),
    })
}
go web web-frameworks gin gin-gonic
1个回答
1
投票

启动路由器时解析所有模板。

router.LoadHTMLFiles("templates/main.html", "templates/userregister.html", "templates/userprofile.html")

然后在你的处理程序中为gin.H{ ... }表达式添加一个布尔变量,例如"isLoggedIn",然后在你的主模板中使用if-else actiontemplate动作。

{{ if .isLoggedIn }}
    {{ template "userprofile" . }}
{{ else }}
    {{ template "userregister" . }}
{{ end }}
© www.soinside.com 2019 - 2024. All rights reserved.