用户主页 封面
Vapor 大型教程

用户主页

本章实现一个「用户主页」:展示用户的基本信息,并列出他创建的所有缩略语。

创建用户主页模板

新建 user.leaf,展示用户名、昵称,以及用表格列出其缩略语(简称 / 全称)。

#set("content") {
<h1>#(user.name)</h1>
<h2>#(user.username)</h2>

#if(count(acronyms) > 0) {
    <table class = "table table-bordered table-hover">
        <thead class="thead-light">
            <tr>
                <th>
                    Short
                </th>
                <th>
                    Long
                </th>
            </tr>
        </thead>
        <tbody>
            #for(acronym in acronyms) {
                <tr>
                    <td>
                        <a href="/acronyms/#(acronym.id)">#(acronym.short)</a>
                    </td>
                    <td>#(acronym.long)</td>
                </tr>
            }
        </tbody>
        } else {
        <h2>There aren't any acronyms yet!</h2>
        }
}

#embed("base")

控制器里加访问逻辑

WebsiteController.swift 定义 UserContext,注册 GET /users/:id 路由。处理方法先用 req.parameters.next(User.self) 取出用户,再 user.acronyms.query(on: req).all() 查出其缩略语。

struct UserContext: Encodable {
    let title: String
    let user: User
    let acronyms: [Acronym]
}
...
    router.get("users", User.parameter, use: userHandler)
...
    func userHandler(_ req: Request) throws -> Future<View> {
        return try req.parameters.next(User.self).flatMap(to: View.self) { user in
            return try user.acronyms.query(on: req).all()
                .flatMap(to: View.self) { acronyms in
                    let context = UserContext(title: user.name, user: user, acronyms: acronyms)
                    return try req.view().render("user", context)
            }
        }
    }

详情页跳转过去

acronym.leaf 中,把创建者名字做成指向用户主页的链接,打通页面之间的跳转。

<p>Created by <a href="/users/#(user.id)/">#(user.name)</a></p>

本系列其他文章