💜 想真正擅长编程? 从一门课程开始,100% 免费

《笔记》第二十八篇 Gin的BBS首页

第28讲 Gin的BBS首页

本讲基于视频实际讲解内容整理


一、本讲概述

前面几讲打好了模板和 controller 的基础。本讲把这些串起来,做出 BBS 的首页:在 controller 里准备帖子数据,通过模板渲染成帖子列表,并结合前面学的公共模板(base / content)展示完整页面。


二、定义帖子数据结构

2.1 Post 结构体

首页要展示帖子列表,先定义数据结构:

Go
// model/post.go(或先放在 controller 里)
package model

type Post struct {
    ID      int
    Title   string   // 标题(大写才能被模板访问)
    Author  string   // 作者
    Content string   // 内容
    Time    string   // 发布时间
}

老师说明:字段必须大写开头,模板才能读到。这里的 model 包用于存放数据结构,后续接入数据库(GORM)时直接复用。


三、在 controller 中准备数据

3.1 准备首页数据

目前还没有接数据库,先在 controller 里准备一些模拟数据,把"取数据"这一步留好位置,以后替换成数据库查询即可:

Go
// controller/index.go
package controller

import (
    "github.com/gin-gonic/gin"
    "你的模块名/model"
)

func Index(c *gin.Context) {
    // TODO: 后续会替换为数据库查询
    posts := []model.Post{
        {ID: 1, Title: "欢迎来到BBS", Author: "管理员", Content: "这是第一帖", Time: "2026-07-14"},
        {ID: 2, Title: "Gin框架好用吗", Author: "张三", Content: "挺好用的", Time: "2026-07-15"},
        {ID: 3, Title: "Go接口怎么学", Author: "李四", Content: "多看多练", Time: "2026-07-16"},
    }

    c.HTML(200, "index.html", gin.H{
        "posts": posts,
        "username": "张三",
    })
}

老师强调:这里故意把"准备数据"单独写成一块,是为了和后面的数据库查询对应上。等学到 GORM(第36讲),只要把 posts 的赋值换成查库即可,页面渲染代码不用改。


四、渲染首页模板

4.1 首页模板(基于公共布局)

结合第26讲学的公共模板,首页只需定义 content:

HTML
<!-- templates/index.html -->
{{define "content"}}
<div class="posts">
    <h2>最新帖子</h2>
    {{range .posts}}
    <div class="post">
        <h3><a href="/post/{{.ID}}">{{.Title}}</a></h3>
        <p>作者:{{.Author}} | 时间:{{.Time}}</p>
        <p>{{.Content}}</p>
    </div>
    {{end}}
</div>
{{end}}
{{template "base" .}}

关键点:{{range .posts}} 遍历帖子切片,循环体内的 . 表示当前 Post,用 {{.Title}}、{{.Author}} 取字段。

4.2 空列表的处理

如果帖子为空,可以用 {{if}} 给出提示:

HTML
{{if .posts}}
    {{range .posts}}
        <div class="post"><h3>{{.Title}}</h3></div>
    {{end}}
{{else}}
    <p>还没有帖子,快来发第一帖吧!</p>
{{end}}

五、main.go 中注册首页路由

Go
func main() {
    gin.SetMode(gin.ReleaseMode)
    r := gin.Default()

    r.LoadHTMLGlob("templates/*")
    r.Static("/static", "./static")

    r.GET("/", controller.Index)

    r.Run(":8080")
}

老师提醒:首页路由通常是 /,用 GET 方法。访问 http://localhost:8080/ 就能看到渲染好的帖子列表。


六、本讲小结

知识点 要点
数据结构 定义 Post 结构体(字段大写)
准备数据 controller 中组装数据(后续换数据库)
渲染列表 {{range .posts}} 遍历
公共模板 首页只写 content,套用 base
空数据处理 {{if .posts}}...{{else}}...{{end}}
路由 r.GET("/", controller.Index)

七、课后练习

  1. 定义 Post 结构体,至少包含 ID、标题、作者、内容、时间
  2. 在 Index 函数中准备 3~5 条模拟帖子数据,用 c.HTML 传给模板
  3. 用 {{range}} 在首页模板中渲染帖子列表,显示标题、作者、时间
  4. 结合第26讲,让首页套用公共 base 布局
  5. 加上 {{if .posts}}...{{else}}...{{end}} 处理空列表
  6. 启动项目访问首页,确认帖子列表正确显示