Golang의 echo(template) 사용
다음 페이지를 참조했습니다.
[Go] 에코의 템플릿 사용법 노트
다음과 같은 구성 파일입니다.
├── server.go
└── views
├── header.html
└── page1.html
server.go// ---------------------------------------------------------------------
/*
server.go
Jun/11/2018
*/
// ---------------------------------------------------------------------
package main
import(
"html/template"
"net/http"
"io"
"github.com/labstack/echo"
)
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)
}
// ---------------------------------------------------------------------
// サイトで共通情報
type ServiceInfo struct {
Title string
}
var serviceInfo = ServiceInfo {
"サイトのタイトル",
}
// ---------------------------------------------------------------------
func main() {
t := &Template{
templates: template.Must(template.ParseGlob("views/*.html")),
}
e := echo.New()
e.Renderer = t
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "こんにちは!")
})
e.GET("/page1", func(c echo.Context) error {
// テンプレートに渡す値
data := struct {
ServiceInfo
Content_a string
Content_b string
Content_c string
Content_d string
} {
ServiceInfo: serviceInfo,
Content_a: "雨が降っています。",
Content_b: "明日も雨でしょうか。",
Content_c: "台風が近づいています。",
Content_d: "Jun/11/2018",
}
return c.Render(http.StatusOK, "page1", data)
})
e.Logger.Fatal(e.Start(":1323"))
}
// ---------------------------------------------------------------------
views/header.html{{define "header"}}
<h1>{{.ServiceInfo.Title}}</h1>
{{end}}
views/page1.html{{define "page1"}}
{{template "header" .}}
<blockquote>
<div>{{.Content_a}}</div>
<div>{{.Content_b}}</div>
<div>{{.Content_c}}</div>
<div>{{.Content_d}}</div>
</blockquote>
{{end}}
서버 시작go run server.go
클라이언트에서http://localhost:1323/page1
방문하다.
다음 버전을 확인했습니다.
$ go version
go version go1.13.6 linux/amd64
Reference
이 문제에 관하여(Golang의 echo(template) 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/ekzemplaro/items/cf58fb01566731d8c597텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)