You can insert a Javascript code into the HTML page (e.g. in the <head>
section) where you create Javascript variables, and initialize them with the parameters passed to the template execution.
See this example:
func main() {
t := template.Must(template.New("").Parse(templ))
m := map[string]interface{}{
"title": "Test page",
"username": "bob",
"counter": 12,
}
if err := t.Execute(os.Stdout, m); err != nil {
panic(err)
}
}
const templ = `<html><head>
<script>
var _title = {{.title}};
var _username = {{.username}};
var _counter = {{.counter}};
</script>
</head><body>
</body>
</html>`
This results in an HTML document (try it on the Go Playground):
<html><head>
<script>
var _title = "Test page";
var _username = "bob";
var _counter = 12 ;
</script>
</head><body>
</body>
</html>
What this means is that other Javascript code in the page (either inlined or referenced, external) will see the variables _title
, _username
, _counter
and use them as regular variables, and they are initialized with values we passed to Template.Execute()
.
Note that the html/template
package performs contextual escaping. See that it inserted the result of {{.title}}
in quotes because it is a string
and that is how it should be written in Javascript code, but no quotes were added when inserting the result of {{.counter}}
, because it is a value of type int
.
Also note that you should use a unique naming strategy to avoid collision with existing variables or variables that may be used in other Javascript code. Usually a special prefix (or postfix) does it.
Also check out this related question: Referencing Go array in Javascript