Golang Echo Labstack 如何在模板视图中调用函数/方法

huangapple go评论76阅读模式
英文:

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
		&quot;AddTS&quot;: util.AddTS,
		&quot;Encrypt&quot;: util.EncryptGeneral,
		&quot;CombineVariable&quot;: util.CombineVariable,
	})
	
	r.Static(&quot;/static&quot;, &quot;./static&quot;)
	r.LoadHTMLFiles(&quot;static/*/*&quot;) //  load the static path
	r.LoadHTMLGlob(&quot;templates/*/*&quot;)

	route.Routes(r)
    r.Run()
}

and in my template view, I could simply call any of my custom functions like this.

range {{ .Data }}
    &lt;div&gt;
        {{ .data_value | AddTS }}
        {{ .data_value | OtherCustomFunction }}
    &lt;/div&gt;
{{ 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[&quot;reverse&quot;] = c.Echo().Reverse
	}

	return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
	e := echo.New()

	renderer := &amp;TemplateRenderer{
		templates: template.Must(template.ParseGlob(&quot;templates/*/*.tmpl&quot;)),
	}
	e.Renderer = renderer

	e.Static(&quot;/static&quot;, &quot;static&quot;)
	
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Logger.Fatal(e.Start(&quot;:8183&quot;))
}

*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 (
    &quot;html/template&quot;
    // ...
)

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[&quot;reverse&quot;] = 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 := &amp;TemplateRenderer{
    templates: template.Must(template.New(&quot;t&quot;).Funcs(template.FuncMap{
        &quot;AddTS&quot;:           util.AddTS,
        &quot;Encrypt&quot;:         util.EncryptGeneral,
        &quot;CombineVariable&quot;: util.CombineVariable,
    }).ParseGlob(&quot;templates/*/*.tmpl&quot;)),
}

huangapple
  • 本文由 发表于 2022年7月11日 00:00:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/72929883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定