How can i use a json object in golang template

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

How can i use a json object in golang template

问题

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

template.html

  1. <html>
  2. <body>
  3. <div id="app">
  4. <test-component :test="{{index . obj}}"></test-component>
  5. </div>
  6. </body>
  7. </html>

server.go

  1. package main
  2. import (
  3. "html/template"
  4. "io"
  5. "net/http"
  6. "github.com/labstack/echo/v4"
  7. )
  8. // TemplateRenderer是Echo框架的自定义html/template渲染器
  9. type TemplateRenderer struct {
  10. templates *template.Template
  11. }
  12. // Render渲染模板文档
  13. func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
  14. // 如果数据是一个map,则添加全局方法
  15. if viewContext, isMap := data.(map[string]interface{}); isMap {
  16. viewContext["reverse"] = c.Echo().Reverse
  17. }
  18. return t.templates.ExecuteTemplate(w, name, data)
  19. }
  20. func main() {
  21. e := echo.New()
  22. renderer := &TemplateRenderer{
  23. templates: template.Must(template.ParseGlob("*.html")),
  24. }
  25. e.Renderer = renderer
  26. // 命名路由"foobar"
  27. e.GET("/something", func(c echo.Context) error {
  28. jsonStr := `{"a":"apple", "b":"banana"}`
  29. obj := map[string]string{}
  30. json.Unmarshal([]byte(jsonStr), &obj)
  31. return c.Render(http.StatusOK, "template.html", obj)
  32. }).Name = "foobar"
  33. e.Logger.Fatal(e.Start(":8000"))
  34. }
英文:

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

  1. &lt;html&gt;
  2. &lt;body&gt;
  3. &lt;div id=&quot;app&quot;&gt;
  4. &lt;test-component :test=&quot;{{index . obj}}&quot;&gt;&lt;/test-component&gt;
  5. &lt;/div&gt;
  6. &lt;/body&gt;
  7. &lt;/html&gt;

server.go

  1. package main
  2. import (
  3. &quot;html/template&quot;
  4. &quot;io&quot;
  5. &quot;net/http&quot;
  6. &quot;github.com/labstack/echo/v4&quot;
  7. )
  8. // TemplateRenderer is a custom html/template renderer for Echo framework
  9. type TemplateRenderer struct {
  10. templates *template.Template
  11. }
  12. // Render renders a template document
  13. func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
  14. // Add global methods if data is a map
  15. if viewContext, isMap := data.(map[string]interface{}); isMap {
  16. viewContext[&quot;reverse&quot;] = c.Echo().Reverse
  17. }
  18. return t.templates.ExecuteTemplate(w, name, data)
  19. }
  20. func main() {
  21. e := echo.New()
  22. renderer := &amp;TemplateRenderer{
  23. templates: template.Must(template.ParseGlob(&quot;*.html&quot;)),
  24. }
  25. e.Renderer = renderer
  26. // Named route &quot;foobar&quot;
  27. e.GET(&quot;/something&quot;, func(c echo.Context) error {
  28. jsonStr := `{&quot;a&quot;:&quot;apple&quot;, &quot;b&quot;:&quot;banana&quot;}`
  29. obj := map[string]string{}
  30. json.Unmarshal([]byte(jsonStr), &amp;obj)
  31. return c.Render(http.StatusOK, &quot;template.html&quot;, obj)
  32. }).Name = &quot;foobar&quot;
  33. e.Logger.Fatal(e.Start(&quot;:8000&quot;))
  34. }

答案1

得分: 1

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

  1. package main
  2. import (
  3. "html/template"
  4. "io"
  5. "net/http"
  6. "github.com/labstack/echo/v4"
  7. "github.com/labstack/echo/v4/middleware"
  8. )
  9. type Template struct {
  10. templates *template.Template
  11. }
  12. func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
  13. t.templates.Delims("[[", "]]")
  14. return t.templates.ExecuteTemplate(w, name, data)
  15. }
  16. func Hello(c echo.Context) error {
  17. test := `{
  18. "name" : "Ben",
  19. "country" : "Germany",
  20. "city" : "Berlin",
  21. "body":{"test":"test","test2":"test2"}
  22. }`
  23. return c.Render(http.StatusOK, "hello", test)
  24. }
  25. func main() {
  26. // Echo 实例
  27. e := echo.New()
  28. t := &Template{
  29. templates: template.Must(template.ParseGlob("public/views/*.html")),
  30. }
  31. e.Renderer = t
  32. e.GET("/hello", Hello)
  33. // 中间件
  34. e.Use(middleware.Logger())
  35. e.Use(middleware.Recover())
  36. // 启动服务器
  37. e.Logger.Fatal(e.Start(":8000"))
  38. }

HTML

  1. {{define "hello"}}
  2. <!doctype html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="utf-8">
  6. <script>
  7. console.log("golangVar");
  8. var golangVar = '{{.}}';
  9. console.log(golangVar);
  10. </script>
  11. </head>
  12. <body>
  13. {{.}}
  14. </body>
  15. </html>
  16. {{end}}
英文:

I found the solution, the template was wrong.

  1. package main
  2. import (
  3. &quot;html/template&quot;
  4. &quot;io&quot;
  5. &quot;net/http&quot;
  6. &quot;github.com/labstack/echo/v4&quot;
  7. &quot;github.com/labstack/echo/v4/middleware&quot;
  8. )
  9. type Template struct {
  10. templates *template.Template
  11. }
  12. func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
  13. t.templates.Delims(&quot;[[&quot;, &quot;]]&quot;)
  14. return t.templates.ExecuteTemplate(w, name, data)
  15. }
  16. func Hello(c echo.Context) error {
  17. test := `{
  18. &quot;name&quot; : &quot;Ben&quot;,
  19. &quot;country&quot; : &quot;Germany&quot;,
  20. &quot;city&quot; : &quot;Berlin&quot;,
  21. &quot;body&quot;:{&quot;test&quot;:&quot;test&quot;,&quot;test2&quot;:&quot;test2&quot;}
  22. }`
  23. return c.Render(http.StatusOK, &quot;hello&quot;, test)
  24. }
  25. func main() {
  26. // Echo instance
  27. e := echo.New()
  28. t := &amp;Template{
  29. templates: template.Must(template.ParseGlob(&quot;public/views/*.html&quot;)),
  30. }
  31. e.Renderer = t
  32. e.GET(&quot;/hello&quot;, Hello)
  33. // Middleware
  34. e.Use(middleware.Logger())
  35. e.Use(middleware.Recover())
  36. // Start server
  37. e.Logger.Fatal(e.Start(&quot;:8000&quot;))
  38. }

HTML

  1. {{define &quot;hello&quot;}}
  2. &lt;!doctype html&gt;
  3. &lt;html lang=&quot;en&quot;&gt;
  4. &lt;head&gt;
  5. &lt;meta charset=&quot;utf-8&quot;&gt;
  6. &lt;script&gt;
  7. console.log(&quot;golangVar&quot;);
  8. var golangVar = &#39;{{.}}&#39;
  9. console.log(golangVar);
  10. &lt;/script&gt;
  11. &lt;/head&gt;
  12. &lt;body&gt;
  13. {{.}}
  14. &lt;/body&gt;
  15. &lt;/html&gt;
  16. {{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:

确定