一,安装模板库
$ go get github.com/gofiber/template/html/v2
go: downloading github.com/gofiber/template/html/v2 v2.1.2
go: downloading github.com/gofiber/utils v1.1.0
go: added github.com/gofiber/template/html/v2 v2.1.2
go: added github.com/gofiber/utils v1.1.0
二,代码
1,routes.go
package routesimport ("github.com/gofiber/fiber/v2""github.com/gofiber/fiber/v2/middleware/recover""github.com/gofiber/template/html/v2""industry/config""industry/controller"
)func SetupRoutes() *fiber.App {// 初始化 HTML 模板引擎viewEngine := html.New("./views", ".html")// 创建 Fiber 应用app := fiber.New(fiber.Config{Views: viewEngine,})app.Use(recover.New())//文章模块articleController := controller.NewArticleController()article := app.Group("/article")article.Get("/info", articleController.GetArticle)//找不到路径时的处理app.Use(func(c *fiber.Ctx) error {return c.Status(fiber.StatusNotFound).JSON(config.Error("不存在的访问路径"))})return app
}
2,controller
func (dc *ArticleController) GetArticle(c *fiber.Ctx) error {// 处理获取文章的逻辑article := new(Article)article.Id = 1article.Title = "三国演义金圣叹批本"article.Author = "罗贯中"//return c.Status(200).JSON(config.Success(artilce))return c.Render("article/info", fiber.Map{"Title": article.Title,"Article":article,})
}
3,view
<!DOCTYPE html>
<html lang=""><head><meta charset="utf-8"><title></title></head><body><header></header><main><h1>{{.Title}}</h1><h2>{{.Article.Author}}</h2></main><footer></footer></body>
</html>
三,测试效果: