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

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

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

图片转代码服务由CSDN问答提供 功能建议

我使用以下代码

  var数据结构{\  n文件FZR 
 API API 
} 
 
 
const tmpl =`
 {{-range .File.Modules}} 
#在{{.Name}} 
 
 echo {{  .EchoText}} 
 {{end}}`
 
func EchoText(m mts)字符串{
返回m.Type 
} 
   
 
 

像这样,它不起作用,现在我将其更改为

  func(m mts)EchoText()字符串{
 return m.Type 
} 
    
 
 

它可以工作,但我想使其与第一个选项一起工作,我该怎么做? 我的意思是更新模板...

更新:作为批准答案 https://golang.org/pkg/text/template/#example_Template_func

但是只有字符串,我该如何注册 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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题