description: Fiber supports server-side template engines.

📝 Templates

Template interfaces

Fiber provides a Views interface to provide your own template engine:

  1. type Views interface {
  2. Load() error
  3. Render(io.Writer, string, interface{}, ...string) error
  4. }

Views interface contains a Load and Render method, Load is executed by Fiber on app initialization to load/parse the templates.

  1. // Pass engine to Fiber's Views Engine
  2. app := fiber.New(fiber.Config{
  3. Views: engine,
  4. // Views Layout is the global layout for all template render until override on Render function.
  5. ViewsLayout: "layouts/main"
  6. })

The Render method is linked to the ctx.Render() function that accepts a template name and binding data. It will use global layout if layout is not being defined in Render function

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. return c.Render("index", fiber.Map{
  3. "hello": "world",
  4. });
  5. })

Engines

Fiber team maintains templates package that provides wrappers for multiple template engines:

  1. package main
  2. import (
  3. "log"
  4. "github.com/gofiber/fiber/v2"
  5. "github.com/gofiber/template/html"
  6. )
  7. func main() {
  8. // Initialize standard Go html template engine
  9. engine := html.New("./views", ".html")
  10. app := fiber.New(fiber.Config{
  11. Views: engine,
  12. })
  13. app.Get("/", func(c *fiber.Ctx) error {
  14. // Render index template
  15. return c.Render("index", fiber.Map{
  16. "Title": "Hello, World!",
  17. })
  18. })
  19. log.Fatal(app.Listen(":3000"))
  20. }
  1. <!DOCTYPE html>
  2. <body>
  3. <h1>{{.Title}}</h1>
  4. </body>
  5. </html>