简体   繁体   中英

How to set web template variable to a dynamic html&golang code?

I have two web page on golang and I want to embed this pages codes to {{.content}} variable (defined in templates/main.html) being with dynamic according to the coming requests.

For example if the guest enter the userregister page I want to the {{.content}} variable will be userregister codes otherwise userprofile codes.

templates/userregister.html page codes;

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

templates/userprofile.html page codes;

{{ 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 }}

The userregister page controller;

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

The userprofile page controller;

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

Parse all templates when starting the router.

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

Then in your handler add to the gin.H{ ... } expression a boolean variable, eg "isLoggedIn" , and then in your main template use an if-else action together with the template action.

{{ if .isLoggedIn }}
    {{ template "userprofile" . }}
{{ else }}
    {{ template "userregister" . }}
{{ end }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM