I have a Go project use GoFiber and html template engine. When I give an array to range block in .html file, if between {{range .}} and {{end}} has no HTML tag, it runs. But when I add some, it seems to consider HTML tag as a field and return error.
connect.go
package database
var Database *gorm.DB
func Connect() error {
var err error
p := config.String("DB_PORT")
port, err := strconv.ParseUint(p, 10, 32)
if err != nil {
log.Println("Invalid DB_PORT param")
}
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
config.String("DB_USERNAME"),
config.String("DB_PASSWORD"),
config.String("DB_HOST"),
port,
config.String("DB_DATABASE"))
Database, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
})
if err != nil {
panic(err)
}
return nil
}
main.go
pakage main
func main() {
// Init App
database.Connect()
// Init Fiber App
app := fiber.New()
// Register router
app.Get("/posts", controller.GetPost)
// Fiber App listen port
app.Listen(":3000")
}
post.go
pakage model
type Post struct {
Id uint64 `json:"id" gorm:"primary_key;auto_increment"`
Content string `json:"content" gorm:"size:255"`
AuthorId uint64 `json:"author_id" gorm:"foreignKey:AuthorID;references:users(id)"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
postController.go
pakage controller
func GetPost(c *fiber.Ctx) error {
var posts []model.Post
database.Database.Find(&posts)
return c.Render("views/feed.html", fiber.Map{
"Posts": posts,
})
}
views/feed.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
{{range .Posts}}
<p>{{.Content}}</p>
{{end}}
</body>
</html>
It returns error: failed to execute: template: :13:5: executing "" at <. <p>>: can't evaluate field <p> in type model.Post