Can someone please guide how can I get a value of a function in a html template?
Suppose the function is :
func GetHello(name string) string {
msg :="Hello I am "+name
return msg
}
in Template… Is there any way to Call the function like: {{.GetHello "Tom"}}
I know I can add it in Golang like below:
type Hello struct {
Val string
}
func Hello_New(w http.ResponseWriter, r *http.Request) {
n := Hello{}
n.Val = GetHello()
tmpl.ExecuteTemplate(w, "MyPage", n)
}
Actually, I need the above functionality to use it with Javascript onchange event. Like, on change, fetch value of selected option, pass it to JS variable, pass that value to Golang func and get its value.
AJAX would be the way to do this anyway so that’s good that you worked that out.
I’ll just point out that in the above, you weren’t actually calling a Go function since you were using .GetMeSthfromDB instead of GetMeSthfromDB and since when passing vars that don’t exist into a template it just evaluates to nothing, you wouldn’t have seen any errors about it.
However, even if you had used that correctly, it would not work the way you expected, since the template and functions are evaluated before the page loads, so you couldn’t use the function to interact with your other code anyway like that. For example if you run this locally (https://play.golang.org/p/JaYe9XjKlY), you’ll see that clicking the button won’t actually do what you want it to do, but rather the function will get executed before the page loads and the jQuery part will be left with this for it’s function: