gofiber: 使用模板

一,安装模板库

$ 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 routes

import (
	"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 = 1
	article.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>

 

三,测试效果:

 

posted @ 2024-11-16 20:15  刘宏缔的架构森林  阅读(4)  评论(0编辑  收藏  举报