douleng0794 2018-05-01 10:52 采纳率: 0%
浏览 40
已采纳

在模板中使用函数代替方法

I use the following code

var data struct {
    File FZR
    API  API
}


const tmpl = `
    {{- range .File.Modules}}
     # in context of {{.Name}}

        echo {{.EchoText}}
    {{end}}`

func  EchoText(m mts) string {
    return m.Type
}

and like this its not working, now I change it to

func (m mts) EchoText() string {
    return m.Type
} 

it will work but I want to make it work with the first option, how can I do it ? I mean update the template ...

update: as approva answer https://golang.org/pkg/text/template/#example_Template_func

but there is only string, how can I register the EchoText

  • 写回答

1条回答 默认 最新

  • doudi2005 2018-05-03 07:13
    关注

    As @mkopriva suggested in his first comment you just have to reference all your functions into a template.FuncMap where you establish the mapping from names to functions

    Then into the template you just need to call them passing them the mts as parameter.

    package main
    
    import (
        "log"
        "os"
        "text/template"
    )
    
    type mts struct {
        Type1 string
        Type2 string
    }
    
    func main() {
        funcMap := template.FuncMap{
            "myFunc1": EchoType1,
            "myFunc2": EchoType2,
        }
    
        const templateText = `
    Input: {{printf "%q" .}}
    Output1:{{myFunc1 .}}
    Output2:{{myFunc2 .}}
    `
    
        tmpl, err := template.New("myFuncTest").Funcs(funcMap).Parse(templateText)
        if err != nil {
            log.Fatalf("parsing: %s", err)
        }
    
        myMts := mts{Type1: "myType1", Type2: "myType2"}
        err = tmpl.Execute(os.Stdout, myMts)
        if err != nil {
            log.Fatalf("execution: %s", err)
        }
    }
    
    func EchoType1(m mts) string {
        return m.Type1
    }
    
    func EchoType2(m mts) string {
        return m.Type2
    }
    

    This will produce the following output :

    Input: {"myType1" "myType2"}

    Output1:myType1

    Output2:myType2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?