LoginSignup
4
10

More than 3 years have passed since last update.

Golang の echo を使う (template)

Last updated at Posted at 2018-06-11

echo で template を使う例です。
次のページを参考にしました。
【Go】Echoでのテンプレート(html/template)の使い方メモ

次のようにファイルを配置します。

├── 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
にアクセスします。
echo_jun1102.png

次のバージョンで確認しました。

$ go version
go version go1.13.6 linux/amd64
4
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
10