Golang의 echo(template) 사용

8308 단어 Goechotemplate
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

좋은 웹페이지 즐겨찾기