【问题标题】:How to set a variable for an external HTML template in Go?如何在 Go 中为外部 HTML 模板设置变量?
【发布时间】:2020-08-15 02:50:33
【问题描述】:

我有两个 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"
    })
})

这并不理想,因为我必须为每个网页设置参数。如何从register.html 设置top.html 中的title?我更喜欢看起来像这样的东西:

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

当然,上面的代码是行不通的。有什么可以实现我想要的吗?

【问题讨论】:

    标签: go go-templates go-gin go-html-template


    【解决方案1】:

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

    func mapset(m map[string]string, key, val string) error {
        m[key] = val
        return nil
    }
    

    然后,在使用Funcs 方法注册它之后,您将使用它来代替{{ set .title = "Register Account" }}:

    {{ (mapset . "title" "Register Account") }}
    

    https://play.golang.com/p/a08OVDpLLH4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 2015-07-06
      • 2012-10-11
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多