You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang Fiber模板渲染异常:仅能渲染index.html,其他模板失效

Fiber 2.50 模板渲染异常:仅能显示index.html,其他模板无法正常渲染

环境信息

  • 系统:Ubuntu 20.04
  • Go版本:1.21.1
  • Fiber版本:2.50

配置与路由代码

config := fiber.Config{
    Views: html.NewFileSystem(http.Dir("./templates"), ".html"),
    ViewsLayout: "main",
}

// 创建Fiber服务器
server := fiber.New(config)

// 添加中间件
server.Use(logger.New())
server.Static("/static", "./static")

// 路由配置
server.Get("/:page", pageViewHandler)
server.Get("/", indexViewHandler)

return server.Listen(":5000")

模板目录结构

templates/
├── main.html
└── pages
    ├── about.html
    └── index.html

index.html和about.html仅显示自身文件名,用于验证渲染的目标模板文件

处理器函数代码

// indexViewHandler 处理首页视图
func indexViewHandler(c *fiber.Ctx) error {
    log.Printf("in indexViewHandler()")
    return c.Render("pages/index", nil)
}

// pageViewHandler 处理其他页面视图
func pageViewHandler(c *fiber.Ctx) error {
    log.Printf("in pageViewHandler()")
    filename := c.Params("page")
    path := fmt.Sprintf("pages/%s", filename)
    log.Printf("path=%s\n", path)
    return c.Render(path, nil)
}

访问日志与异常现象

  1. 访问localhost:5000/时正常显示index页面,日志输出:
2023/11/25 10:33:43 in indexViewHandler()
10:33:43 | 200 |      64.652µs |       127.0.0.1 | GET     | /     
  1. 访问http://localhost:5000/about/时,页面仍显示index内容,但日志显示已调用正确处理器且路径无误:
2023/11/25 10:34:29 in pageViewHandler()
2023/11/25 10:34:29 path=pages/about
10:34:29 | 200 |      60.623µs |       127.0.0.1 | GET     | /about/ 
  1. 访问http://localhost:5000/does-not-exist/时返回404,符合预期。

  2. 手动修改indexViewHandler中的渲染路径为"pages/about",页面依然显示index内容,怀疑存在未定位到的默认配置问题,寻求解决思路。


内容的提问来源于stack exchange,提问作者mszmurlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:04:56