Reputation: 11
I've two Go templates.
top.html
:
<html>
<head>
<title>{{ .title }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
and register.html
:
{{ template "top.html" . }}
<h1>Register account</h1>
...
Currently to set the title I use the function:
r.GET("/register", func(c *gin.Context) {
c.HTML(http.StatusOK, "register.html", gin.H{
"title" : "Register Account"
})
})
This is not ideal as I have to set the parameter for every webpage. How can I set the title
in top.html
from register.html
? I'd much rather have something that looks like:
{{ set .title = "Register Account" }}
{{ template "top.html" . }}
<h1>Register account</h1>
...
Of course, the above code does not work. Is there anything available to achieve what I want?
Upvotes: 1
Views: 1642
Reputation: 38313
You can do this by implementing a template function. For example:
func mapset(m map[string]string, key, val string) error {
m[key] = val
return nil
}
Then, after registering it with the Funcs
method, instead of {{ set .title = "Register Account" }}
you would use it as:
{{ (mapset . "title" "Register Account") }}
https://play.golang.com/p/a08OVDpLLH4
Upvotes: 1