跳到主要内容
版本: v2.x

📝 模板

模板是一个很好的工具,可以在不使用独立前端框架的情况下渲染动态内容。

模板引擎

Fiber 允许你在应用初始化时提供一个自定义模板引擎。

app := fiber.New(fiber.Config{
// Pass in Views Template Engine
Views: engine,

// Default global path to search for views (can be overriden when calling Render())
ViewsLayout: "layouts/main",

// Enables/Disables access to `ctx.Locals()` entries in rendered views
// (defaults to false)
PassLocalsToViews: false,
})

支持的引擎

Fiber 团队维护了一个 templates 包,该包为多个模板引擎提供了封装

信息

自定义模板引擎可以实现 Views 接口以在 Fiber 中获得支持。

Views 接口
type Views interface {
// Fiber executes Load() on app initialization to load/parse the templates
Load() error

// Outputs a template to the provided buffer using the provided template,
// template name, and binded data
Render(io.Writer, string, interface{}, ...string) error
}
注意

Render 方法链接到接受模板名称和绑定数据的 ctx.Render() 函数。

渲染模板

一旦引擎设置完成,路由处理程序就可以调用 ctx.Render() 函数,传入模板名称和绑定数据来发送渲染后的模板。

签名
func (c *Ctx) Render(name string, bind Map, layouts ...string) error
信息

默认情况下,ctx.Render()ViewsLayout 路径中查找模板名称。要覆盖此设置,请在 layouts 参数中提供路径。

app.Get("/", func(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Title": "Hello, World!",
})

})
注意

如果 Fiber 配置选项 PassLocalsToViews 被启用,那么所有使用 ctx.Locals(key, value) 设置的 locals 将传递给模板。使用此设置时,避免键冲突非常重要。

高级模板

自定义函数

Fiber 支持向模板添加自定义函数。

AddFunc

向所有模板添加一个全局函数。

签名
func (e *Engine) AddFunc(name string, fn interface{}) IEngineCore
// Add `ToUpper` to engine
engine := html.New("./views", ".html")
engine.AddFunc("ToUpper", func(s string) string {
return strings.ToUpper(s)
}

// Initialize Fiber App
app := fiber.New(fiber.Config{
Views: engine,
})

app.Get("/", func (c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Content": "hello, world!"
})
})

AddFuncMap

向所有模板添加一个函数映射(按名称键入)。

签名
func (e *Engine) AddFuncMap(m map[string]interface{}) IEngineCore
// Add `ToUpper` to engine
engine := html.New("./views", ".html")
engine.AddFuncMap(map[string]interface{}{
"ToUpper": func(s string) string {
return strings.ToUpper(s)
},
})

// Initialize Fiber App
app := fiber.New(fiber.Config{
Views: engine,
})

app.Get("/", func (c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"Content": "hello, world!"
})
})

完整示例

package main

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

func main() {
// Initialize standard Go html template engine
engine := html.New("./views", ".html")
// If you want to use another engine,
// just replace with following:
// Create a new engine with django
// engine := django.New("./views", ".django")

app := fiber.New(fiber.Config{
Views: engine,
})
app.Get("/", func(c *fiber.Ctx) error {
// Render index template
return c.Render("index", fiber.Map{
"Title": "Go Fiber Template Example",
"Description": "An example template",
"Greeting": "Hello, world!",
});
})

log.Fatal(app.Listen(":3000"))
}