GoFrame 模板引擎-模板变量

2022-04-01 13:51 更新

变量对象

我们可以在模板中使用自定义的对象,并可在模板中访问对象的属性及调用其方法。

示例:

package main

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
)

type T struct {
	Name string
}

func (t *T) Hello(name string) string {
	return "Hello " + name
}

func (t *T) Test() string {
	return "This is test"
}

func main() {
	t := &T{"John"}
	v := g.View()
	content := `{{.t.Hello "there"}}, my name's {{.t.Name}}. {{.t.Test}}.`
	if r, err := v.ParseContent(context.TODO(), content, g.Map{"t": t}); err != nil {
		g.Dump(err)
	} else {
		g.Dump(r)
	}
}

其中,赋值给模板的变量既可以是对象指针也可以是对象变量。但是注意定义的对象方法,如果为对象指针那么只能调用方法接收器为对象指针的方法;如果为对象变量,那么只能调用方法接收器为对象的方法。

执行后,输出结果为:

Hello there, my name's John. This is test.


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号