Created
November 19, 2018 06:29
-
-
Save ykyuen/a8bcf35a338f398ddfe61275ac91e439 to your computer and use it in GitHub Desktop.
setup-nested-html-template-in-go-echo-web-framework-09
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"html/template" | |
"io" | |
"github.com/labstack/echo" | |
"gitlab.com/ykyuen/golang-echo-template-example/handler" | |
) | |
// Define the template registry struct | |
type TemplateRegistry struct { | |
templates map[string]*template.Template | |
} | |
// Implement e.Renderer interface | |
func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c echo.Context) error { | |
tmpl, ok := t.templates[name] | |
if !ok { | |
err := errors.New("Template not found -> " + name) | |
return err | |
} | |
return tmpl.ExecuteTemplate(w, "base.html", data) | |
} | |
func main() { | |
// Echo instance | |
e := echo.New() | |
// Instantiate a template registry with an array of template set | |
// Ref: https://gist.github.com/rand99/808e6e9702c00ce64803d94abff65678 | |
templates := make(map[string]*template.Template) | |
templates["home.html"] = template.Must(template.ParseFiles("view/home.html", "view/base.html")) | |
templates["about.html"] = template.Must(template.ParseFiles("view/about.html", "view/base.html")) | |
e.Renderer = &TemplateRegistry{ | |
templates: templates, | |
} | |
// Route => handler | |
e.GET("/", handler.HomeHandler) | |
e.GET("/about", handler.AboutHandler) | |
// Start the Echo server | |
e.Logger.Fatal(e.Start(":1323")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment