如何在Go中为外部HTML模板设置变量?

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

我有两个Go模板。

top.html

<html>
<head>
    <title>{{ .title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="UTF-8">
</head>
<body>

register.html

{{ template "top.html" . }}
    <h1>Register account</h1>
...

当前使用的功能是设置标题:

r.GET("/register", func(c *gin.Context) {
    c.HTML(http.StatusOK, "register.html", gin.H{
        "title" : "Register Account"
    })
})

这不理想,因为我必须为每个网页设置参数。如何在titletop.html中设置register.html?我宁愿有一些看起来像这样的东西:

{{ set .title = "Register Account" }}
{{ template "top.html" . }}
    <h1>Register account</h1>
...

当然,以上代码不起作用。有什么可以实现我想要的吗?

go go-templates gin go-html-template
1个回答
0
投票

您可以通过实现模板功能来做到这一点。例如:

© www.soinside.com 2019 - 2024. All rights reserved.