How can i use a json object in golang template

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

How can i use a json object in golang template

问题

我的目标是将数据库中的对象作为JSON对象加载到Vue应用程序中,并在golang模板中呈现。数据应直接加载到网页中。有人知道如何做到这一点吗?

template.html

<html>
    <body>
	  <div id="app">
		<test-component :test="{{index . obj}}"></test-component>
	  </div>
    </body>
</html>

server.go

package main

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

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

// TemplateRenderer是Echo框架的自定义html/template渲染器
type TemplateRenderer struct {
	templates *template.Template
}

// Render渲染模板文档
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {

	// 如果数据是一个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("*.html")),
  }
  e.Renderer = renderer

  // 命名路由"foobar"
  e.GET("/something", func(c echo.Context) error {
	jsonStr := `{"a":"apple", "b":"banana"}`
		obj := map[string]string{}

		json.Unmarshal([]byte(jsonStr), &obj)
      		return c.Render(http.StatusOK, "template.html", obj)
  }).Name = "foobar"

  e.Logger.Fatal(e.Start(":8000"))
}
英文:

My goal is to load an object from the database as a json object into a vue application that is rendered in a golang template. The data should be loaded directly into the web page. Does anyone have an idea how to do this?

template.html

&lt;html&gt;
    &lt;body&gt;
	  &lt;div id=&quot;app&quot;&gt;
		&lt;test-component :test=&quot;{{index . obj}}&quot;&gt;&lt;/test-component&gt;
	  &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;

server.go

package main

import (
	&quot;html/template&quot;
	&quot;io&quot;
	&quot;net/http&quot;

	&quot;github.com/labstack/echo/v4&quot;
)

// TemplateRenderer is a custom html/template renderer for Echo framework
type TemplateRenderer struct {
	templates *template.Template
}

// Render renders a template document
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;*.html&quot;)),
  }
  e.Renderer = renderer

  // Named route &quot;foobar&quot;
  e.GET(&quot;/something&quot;, func(c echo.Context) error {
	jsonStr := `{&quot;a&quot;:&quot;apple&quot;, &quot;b&quot;:&quot;banana&quot;}`
		obj := map[string]string{}

		json.Unmarshal([]byte(jsonStr), &amp;obj)
      		return c.Render(http.StatusOK, &quot;template.html&quot;, obj)
  }).Name = &quot;foobar&quot;

  e.Logger.Fatal(e.Start(&quot;:8000&quot;))
}

答案1

得分: 1

我找到了解决方案,模板是错误的。

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")),
	}

	e.Renderer = t
	e.GET("/hello", Hello)

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

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

HTML

{{define "hello"}}
<!doctype html>
<html lang="en">
    
<head>
    <meta charset="utf-8">
    <script>
        console.log("golangVar");
        var golangVar = '{{.}}';
        console.log(golangVar);
    </script>
 </head>
 <body>
    {{.}}
 </body>

</html>
{{end}}
英文:

I found the solution, the template was wrong.

package main

import (
	&quot;html/template&quot;
	&quot;io&quot;
	&quot;net/http&quot;

	&quot;github.com/labstack/echo/v4&quot;
	&quot;github.com/labstack/echo/v4/middleware&quot;
)

type Template struct {
	templates *template.Template
}

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

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

	t := &amp;Template{
		templates: template.Must(template.ParseGlob(&quot;public/views/*.html&quot;)),
	}

	e.Renderer = t
	e.GET(&quot;/hello&quot;, Hello)
	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// Start server
	e.Logger.Fatal(e.Start(&quot;:8000&quot;))
}

HTML

{{define &quot;hello&quot;}}
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
    
&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;script&gt;
        console.log(&quot;golangVar&quot;);
        var golangVar = &#39;{{.}}&#39;
        console.log(golangVar);
    &lt;/script&gt;
 &lt;/head&gt;
 &lt;body&gt;
    {{.}}
 &lt;/body&gt;

&lt;/html&gt;
{{end}}

huangapple
  • 本文由 发表于 2022年9月17日 05:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/73750489.html
匿名

发表评论

匿名网友

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

确定