问题
How can I execute function in templates that returns no value? Here is example:
func main() {
u, err := url.Parse("http://example.com/test?param1=true¶m2=true")
if err != nil {
log.Fatal(err)
}
m := u.Query()
m.Del("param1") // param1 successful deleted!
u.RawQuery = m.Encode()
fmt.Println(u.RawQuery)
const tmpl = `
{{$m := .Query}}
{{$m.Del "param2"}} <!-- failed to delete param2! -->
{{.RawQuery}}
`
t := template.Must(template.New("").Parse(tmpl))
err = t.Execute(os.Stdout, u)
if err != nil {
log.Println("executing template:", err)
}
}
see this code in play.golang.org
I know that in templates shouldn't be much logic, but ignorance of running function that returns no value seems to me interesting issue.
回答1:
Templates in Go are not like those in other languages (e.g. PHP). Use template.FuncMap
to create custom functions for your templates.
package main
import (
"fmt"
"log"
"net/url"
"os"
"text/template"
)
func main() {
funcMap := template.FuncMap{
"delete": deleteMap,
}
u, err := url.Parse("http://example.com/test?param1=true¶m2=true")
if err != nil {
log.Fatal(err)
}
u = deleteMap(u, "param1") // works in regular code and templates
fmt.Println(u.RawQuery)
const tmpl = `
{{$m := delete . "param2"}} <!-- WORKS! -->
{{$m.RawQuery}}
`
t := template.New("").Funcs(funcMap)
t = template.Must(t.Parse(tmpl))
err = t.Execute(os.Stdout, u)
if err != nil {
log.Println("executing template:", err)
}
}
func deleteMap(u *url.URL, key string) *url.URL {
m := u.Query()
m.Del(key) // key successful deleted!
u.RawQuery = m.Encode()
return u
}
Or, try the playground version.
来源:https://stackoverflow.com/questions/31221849/text-template-cant-call-method-function-with-0-results