keyboard_tabSkip to content
listGoAPI Essential

แนะนำ View template

สารบัญ

Template กับ Fiber

Ref: https://docs.gofiber.io/guide/templates

Note

  • Fiber support การ render template ได้
  • โดยมี template ตั้งแต่ html, pug หรือ django ก็สามารถ support ได้หมด

ต้องลงตัวนี้เพิ่ม

bash
go get github.com/gofiber/template/html/v2

ที่ main.go

go
package main

import (
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/template/html/v2"
)

func main() {
  // Initialize standard Go html template engine
  engine := html.New("./views", ".html")

  // Pass the engine to Fiber
  app := fiber.New(fiber.Config{
    Views: engine,
  })

  // Setup route
  app.Get("/", renderTemplate)

  app.Listen(":8080")
}

func renderTemplate(c *fiber.Ctx) error {
  // Render the template with variable data
  return c.Render("template", fiber.Map{
    "Name": "World",
  })
}

ที่ views/template.html

go
<!-- template.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Example Template</title>
</head>
<body>
    <h1>Hello, {{.Name}}!</h1>
</body>
</html>

ผลลัพธ์ view-01

Use case ที่จะได้ใช้

  1. หน้าเว็บที่เราอยาก render แยกเป็นพิเศษ (แยกส่วนกับ Framework หรือ Frontend ออกมา)
  2. Application ที่ support การส่งหรือ render ผ่าน html เช่น email, pdf

** ส่วนใหญ่ถ้าใช้ Framework อยู่แล้วก็จะจัดการผ่าน API มากกว่าจะมาจัดการผ่าน View