英文:
Golang Echo Labstack How to Call a Function / Method in a Template View
问题
我正在使用Golang Echo Labstack框架构建一个前端网站,并且我想在我的模板视图中调用一些自定义函数。我该如何在Echo中实现这个功能呢?
例如,我可以在Gin中这样做:
func main() {
	r := gin.Default()
	r.SetFuncMap(template.FuncMap{
		// 添加自定义函数
		"AddTS":            util.AddTS,
		"Encrypt":          util.EncryptGeneral,
		"CombineVariable":  util.CombineVariable,
	})
	
	r.Static("/static", "./static")
	r.LoadHTMLFiles("static/*/*") // 加载静态路径
	r.LoadHTMLGlob("templates/*/*")
	route.Routes(r)
	r.Run()
}
在我的模板视图中,我可以像这样简单地调用任何自定义函数:
{{ range .Data }}
    <div>
        {{ .data_value | AddTS }}
        {{ .data_value | OtherCustomFunction }}
    </div>
{{ end }}
但是我似乎找不到Echo中类似的方法,我该如何实现一个可以在模板视图中使用的全局函数呢?
这是我当前的Echo文件:
type TemplateRenderer struct {
	templates *template.Template
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	// 如果data是一个map,则添加全局方法
	if viewContext, isMap := data.(map[string]interface{}); isMap {
		viewContext["reverse"] = c.Echo().Reverse
	}
	return t.templates.ExecuteTemplate(w, name, data)
}
func main() {
	e := echo.New()
	renderer := &TemplateRenderer{
		templates: template.Must(template.ParseGlob("templates/*/*.tmpl")),
	}
	e.Renderer = renderer
	e.Static("/static", "static")
	
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Logger.Fatal(e.Start(":8183"))
}
*由于某些原因,我不能在这个项目中使用Gin,必须只使用Echo。
非常感谢。
英文:
I am building a front end website with Golang Echo Labstack framework, and I want to call some custom functions in my template view. How do I do this with Echo?
For example, I am able to do this with Gin
func main() {
	r := gin.Default()
	r.SetFuncMap(template.FuncMap{
        // Add my custom functions
		"AddTS": util.AddTS,
		"Encrypt": util.EncryptGeneral,
		"CombineVariable": util.CombineVariable,
	})
	
	r.Static("/static", "./static")
	r.LoadHTMLFiles("static/*/*") //  load the static path
	r.LoadHTMLGlob("templates/*/*")
	route.Routes(r)
    r.Run()
}
and in my template view, I could simply call any of my custom functions like this.
range {{ .Data }}
    <div>
        {{ .data_value | AddTS }}
        {{ .data_value | OtherCustomFunction }}
    </div>
{{ end }}
But I can't seem to find a similar methods in Echo, how do I implement a global function that I can use in my template views?
Here is my current Echo file
type TemplateRenderer struct {
	templates *template.Template
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	// Add global methods if data is a map
	if viewContext, isMap := data.(map[string]interface{}); isMap {
		viewContext["reverse"] = c.Echo().Reverse
	}
	return t.templates.ExecuteTemplate(w, name, data)
}
func main() {
	e := echo.New()
	renderer := &TemplateRenderer{
		templates: template.Must(template.ParseGlob("templates/*/*.tmpl")),
	}
	e.Renderer = renderer
	e.Static("/static", "static")
	
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Logger.Fatal(e.Start(":8183"))
}
*For some reasons, I cannot use Gin for this project and must only use Echo.
Thanks a lot.
答案1
得分: 3
你可以按照这里的指南,轻松实现自己的渲染器,并使用Go自带的html/template包来管理模板:
import (
    "html/template"
    // ...
)
type TemplateRenderer struct {
    templates *template.Template
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    // 如果data是一个map,则添加全局方法
    if viewContext, isMap := data.(map[string]interface{}); isMap {
        viewContext["reverse"] = c.Echo().Reverse
    }
    return t.templates.ExecuteTemplate(w, name, data)
}
要让模板访问自定义函数,你可以使用Funcs方法,像这样:
renderer := &TemplateRenderer{
    templates: template.Must(template.New("t").Funcs(template.FuncMap{
        "AddTS":           util.AddTS,
        "Encrypt":         util.EncryptGeneral,
        "CombineVariable": util.CombineVariable,
    }).ParseGlob("templates/*/*.tmpl")),
}
英文:
You can easily implement your own renderer, as explained in the guide here, and use Go's own html/template package to manage the templates:
import (
    "html/template"
    // ...
)
type TemplateRenderer struct {
    templates *template.Template
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    // Add global methods if data is a map
    if viewContext, isMap := data.(map[string]interface{}); isMap {
        viewContext["reverse"] = c.Echo().Reverse
    }
    return t.templates.ExecuteTemplate(w, name, data)
}
And to give the templates access to custom functions you can use the Funcs method like so:
renderer := &TemplateRenderer{
    templates: template.Must(template.New("t").Funcs(template.FuncMap{
        "AddTS":           util.AddTS,
        "Encrypt":         util.EncryptGeneral,
        "CombineVariable": util.CombineVariable,
    }).ParseGlob("templates/*/*.tmpl")),
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论