从Go模板调用方法 [英] Call a method from a Go template

查看:114
本文介绍了从Go模板调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

Let's say I have

type Person struct {
  Name string
}
func (p *Person) Label() string {
  return "This is " + p.Name
}

如何从html / template使用此方法?我会在我的模板中需要这样的东西:

How can I use this method from a html/template ? I would need something like this in my template:

{{ .Label() }}


推荐答案

只需省略括号即可。示例:

Just omit the parentheses and it should be fine. Example:

package main

import (
    "html/template"
    "log"
    "os"
)

type Person string

func (p Person) Label() string {
    return "This is " + string(p)
}

func main() {
    tmpl, err := template.New("").Parse(`{{.Label}}`)
    if err != nil {
        log.Fatalf("Parse: %v", err)
    }
    tmpl.Execute(os.Stdout, Person("Bob"))
}

根据 documentation ,您可以调用任何返回一个值(任何类型)或两个值(如果第二个值是类型错误。在后面的例子中,如果非零, Execute 将返回错误,并停止执行模板。

According to the documentation, you can call any method which returns one value (of any type) or two values if the second one is of type error. In the later case, Execute will return that error if it is non-nil and stop the execution of the template.

这篇关于从Go模板调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆