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.Settings{
  3. Views: engine,
  4. })

The Render method is linked to the ctx.Render() function that accepts a template name and binding data.

  1. app.Get("/", func(c *fiber.Ctx) {
  2. if err := c.Render("index", fiber.Map{
  3. "hello": "world",
  4. }); err != nil {
  5. c.Next(err)
  6. }
  7. })

Engines

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

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