How can i use a json object in golang template

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

<html>
    <body>
      <div id="app">
        <test-component :test=""></test-component>
      </div>
    </body>
</html>

server.go

package main

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

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

// 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["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

  // Named route "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"))
}


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation