登录
首页 >  Golang >  Go问答

如何在HTML和Golang代码中实现动态设置Web模板变量?

来源:stackoverflow

时间:2024-03-08 11:36:28 466浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何在HTML和Golang代码中实现动态设置Web模板变量?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我在 golang 上有两个网页,我想将此页面代码嵌入到 {{.content}} 变量(在 templates/main.html 中定义)中,该变量根据即将到来的请求而动态变化。

例如,如果访客进入用户注册页面,我希望 {{.content}} 变量将是用户注册代码,否则是用户配置文件代码。

templates/userregister.html页面代码;

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

templates/userprofile.html页面代码;

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

模板/main.html;

{{ define "main" }}


    {{ template "head" . }}
    
        
{{ template "header" . }}
{{.content}}
{{ template "footer" . }}
{{ 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"),
    })
}

解决方案


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

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>