Text/template: “can't call method/function with 0 results.”

耗尽温柔 提交于 2019-12-25 04:39:17

问题


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&param2=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&param2=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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!