Skip to content

Instantly share code, notes, and snippets.

@akiraak
Created June 18, 2017 03:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akiraak/93a31b2f549381e33a95feee85647dcb to your computer and use it in GitHub Desktop.
Save akiraak/93a31b2f549381e33a95feee85647dcb to your computer and use it in GitHub Desktop.
Echoでtemplateを使う
{{define "base"}}
<html lang="en">
<head>
<title>{{template "title" .}}</title>
</head>
<body>
{{template "body" .}}
</body>
</html>
{{end}}
{{define "title"}}{{.}}{{end}}
{{define "body"}}
{{.}} World!
{{end}}
package ec
import (
"github.com/labstack/echo"
"html/template"
"io"
)
var E = echo.New()
type Template struct {
Templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.Templates.ExecuteTemplate(w, name, data)
}
func CreateTemplate(files []string) *Template {
return &Template{template.Must(template.ParseFiles(files...))}
}
{{define "title"}}{{.}}{{end}}
{{define "body"}}
{{.}} World!
{{end}}
package main
import (
"github.com/akiraak/go-manga/echo"
"github.com/labstack/echo"
"net/http"
)
func main() {
ec.E.Debug = true
ec.E.GET("/hello", func(c echo.Context) error {
ec.E.Renderer = ec.CreateTemplate([]string{
"public/views/base.html",
"public/views/hello.html"})
return c.Render(http.StatusOK, "base", "Hello")
})
ec.E.GET("/byebye", func(c echo.Context) error {
ec.E.Renderer = ec.CreateTemplate([]string{
"public/views/base.html",
"public/views/byebye.html"})
return c.Render(http.StatusOK, "base", "ByeBye")
})
ec.E.Logger.Fatal(ec.E.Start(":1323"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment