GoFrame 模板引擎-模板变量

变量对象

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

示例:

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 names {{.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 names John. This is test.

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/goframe/21048.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年5月18日
下一篇 2023年5月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注


Fatal error: Uncaught JSMin_UnterminatedStringException: JSMin: Unterminated String at byte 489: ", in /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php:214 Stack trace: #0 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(152): JSMin->action() #1 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php(86): JSMin->min() #2 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(257): JSMin::minify() #3 [internal function]: AO_Minify_HTML->_removeScriptCB() #4 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(108): preg_replace_callback() #5 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/ao-minify-html.php(47): AO_Minify_HTML->process() #6 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/autoptimizeHTML.php(105): AO_Minify_HTML::minify() #7 /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/aut in /www/wwwroot/web176.cc/wp-content/plugins/autoptimize/classes/external/php/jsmin.php on line 214