你可以如何在echo Render中更改分隔符?

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

How can i change the Delim in echo Render?

问题

我正在尝试更改Go语言中HTML模板的分隔符。不幸的是,在render函数和main函数中都无法生效。

请参考https://pkg.go.dev/text/template#Template.Delims

package main

import (
	"html/template"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	t.templates.Delims("[[", "]]")
	return t.templates.ExecuteTemplate(w, name, data)
}

func Hello(c echo.Context) error {
	test := `{
		"name" : "Ben",
		"country" : "Germany",
		"city" : "Berlin",
		"body":{"test":"test","test2":"test2"}
	}`
	return c.Render(http.StatusOK, "hello", test)
}

func main() {
	// Echo实例
	e := echo.New()

	t := &Template{
		templates: template.Must(template.ParseGlob("public/views/*.html")),
	}
	t.templates.Delims("[[", "]]")
	e.Renderer = t
	e.GET("/hello", Hello)

	// 中间件
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// 启动服务器
	e.Logger.Fatal(e.Start(":8000"))
}

希望对你有帮助!

英文:

i am trying to change the delimiter for go in an html template. Unfortunately, it does not work in the render function, nor in the main function.

See https://pkg.go.dev/text/template#Template.Delims

package main

import (
	"html/template"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	t.templates.Delims("[[", "]]")
	return t.templates.ExecuteTemplate(w, name, data)
}
func Hello(c echo.Context) error {
	test := `{
        "name" : "Ben",
        "country" : "Germany",
        "city" : "Berlin",
		"body":{"test":"test","test2":"test2"}
    }`
	return c.Render(http.StatusOK, "hello", test)
}

func main() {
	// Echo instance
	e := echo.New()

	t := &Template{
		templates: template.Must(template.ParseGlob("public/views/*.html")),
	}
	t.templates.Delims("[[", "]]")
	e.Renderer = t
	e.GET("/hello", Hello)
	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// Start server
	e.Logger.Fatal(e.Start(":8000"))
}

答案1

得分: 1

你必须在调用ParseGlob之前调用Delims方法。
像这样:

	t := &Template{
		templates: template.Must(template.New("").Delims("[[", "]]").ParseGlob("public/views/*.html")),
	}
英文:

You must call Delims before ParseGlob.
like this:

	t := &Template{
		templates: template.Must(template.New("").Delims("[[", "]]").ParseGlob("public/views/*.html")),
	}

huangapple
  • 本文由 发表于 2022年9月18日 16:04:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73761041.html
匿名

发表评论

匿名网友

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

确定