πŸ“
Templates
Fiber supports server-side template engines.

Template interfaces

Fiber provides a Views interface to provide your own template engine:
Views
1
type Views interface {
2
Load() error
3
Render(io.Writer, string, interface{}, ...string) error
4
}
Copied!
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
})
Copied!
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
})
Copied!

Engines

Fiber team maintains templates package that provides wrappers for multiple template engines:
example
views/index.html
1
package main
2
​
3
import (
4
"log"
5
"github.com/gofiber/fiber/v2"
6
"github.com/gofiber/template/html"
7
)
8
​
9
func main() {
10
// Initialize standard Go html template engine
11
engine := html.New("./views", ".html")
12
​
13
app := fiber.New(fiber.Config{
14
Views: engine,
15
})
16
app.Get("/", func(c *fiber.Ctx) error {
17
// Render index template
18
return c.Render("index", fiber.Map{
19
"Title": "Hello, World!",
20
})
21
})
22
​
23
log.Fatal(app.Listen(":3000"))
24
}
Copied!
1
<!DOCTYPE html>
2
<body>
3
<h1>{{.Title}}</h1>
4
</body>
5
</html>
Copied!
Last modified 5mo ago