0
0

More than 1 year has passed since last update.

【Golang】Echoのテンプレートレンダリングでちょっとはまった話

Posted at

https://echo.labstack.com/guide/templates/#template-rendering
上記を参考に実装したがInternal Server Errorが出てしまってちょっぴりつまずいたところの記事。

結論だけ知りたい人向け

c.Render(http.StatusOK, "index", nil) // no data passed
で本来"index.html"として指定すべきところを"index"として指定していた。
indexとして指定するのであれば、表示させたい箇所(基本的には対象のファイルの全部だと思うが)を
{{define "index"}}と{{end}}で囲む必要があった

ソースコード

フォルダ構成はこんな感じ
├─public
│ └─views
│ └─ index.html
└─main.go

ソースコードはそれぞれ以下のように記述

main.go

package main

import (
	"html/template"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"
)

type TemplateRegistry struct {
	templates *template.Template
}

func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
	e := echo.New()

	// Initialize a new template registry and register all html templates
	reg := &TemplateRegistry{
		templates: template.Must(template.ParseGlob("public/views/*.html")),
	}
	e.Renderer = reg

	e.GET("/", func(c echo.Context) error {
		return c.Render(http.StatusOK, "index", nil) // no data passed
	})

	e.Logger.Fatal(e.Start(":1323"))
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Welcome Page</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>

解決までの流れ

最近は詰まるとChatGPT君に質問しているのだが、質問したところ

	e.Debug = true // enable debug mode

を挿入するとデバッグ表示が出るということで、上記を挿入して実行

{
  "error": "html/template: \"index\" is undefined",
  "message": "Internal Server Error"
}

やはりテンプレートのレンダリングの部分で指定がおかしそう。
"index"の指定がおかしいのかと思って該当箇所を以下のように修正したところ、意図通りにページが表示された。

return c.Render(http.StatusOK, "index", nil) // no data passed
0
0
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
0
0