如何创建和使用布局模板(Layout)实现页面统一布局
解读
在国内 Buffalo 岗位面试中,这道题考察的是“视图层工程化”能力。Buffalo 默认把布局模板放在 templates/_layout.plush.html,所有页面默认继承该文件。面试官想确认你能否:
- 按国内团队规范(前后端分离但共用模板)组织目录
- 用 partial 与 block 实现可插拔区域(如导航、广告位)
- 在多语言、多主题场景下动态切换布局
- 兼顾性能(预编译、缓存)与可维护性(组件化)
知识点
- 布局文件命名与存放路径:templates/_layout.plush.html 为默认,其他布局需以 _ 开头、.plush.html 结尾
- 继承语法:<%= contentOf("main") %> 占位,子页面用 <% contentFor("main") { %> ... <% } %> 注入
- 多布局切换:在 actions 里 c.Set("layout", "admin"),Buffalo 会优先找 templates/_admin.plush.html
- 局部组件:<%= partial("shared/nav.plush.html", {user: currentUser}) %>,实现头部、底部复用
- 国际化:layouts 里使用 <%= t("nav.home") %>,配合 i18n 文件自动切换
- 静态资源管道:layouts 里用 <%= javascriptTag("app.js") %> / <%= stylesheetTag("app.css") %>,Webpack 热重载自动注入 hash
- 性能优化:buffalo build 时 plush 模板预编译为 go 代码,生产环境无运行时解析损耗
答案
步骤一:创建默认布局
templates/_layout.plush.html
步骤二:子页面使用布局
templates/users/index.plush.html
<% contentFor("main") { %>
<h1><%= t("user.list") %></h1>
...
<% } %>
步骤三:在 action 中注入变量
func UsersIndex(c buffalo.Context) error {
c.Set("title", "用户列表")
c.Set("lang", "zh-cn")
c.Set("currentUser", getCurrentUser(c))
return c.Render(http.StatusOK, r.HTML("users/index.plush.html"))
}
步骤四:按需切换布局
func AdminIndex(c buffalo.Context) error {
c.Set("layout", "admin") // 使用 templates/_admin.plush.html
return c.Render(http.StatusOK, r.HTML("admin/index.plush.html"))
}
步骤五:生产环境验证
buffalo build 后,查看 bin 文件已包含预编译模板;在 docker 镜像里删除 templates 目录仍能正常运行,证明无运行时依赖
拓展思考
- 主题化:把 _layout.plush.html 拆成 _layout.<theme>.plush.html,通过域名或 Cookie 决定 theme 变量,实现“黑白模式”切换,满足国内运营活动快速换肤需求
- 微前端嵌入:在 layouts 里预留 <%= yieldMicro("react-header") %>,通过 buffalo 反向代理把 React 子应用片段注入同一布局,兼顾 SEO 与单页体验
- 缓存策略:对不常变动的 partial(如 footer)使用 redis 缓存渲染结果,并在 CMS 后台提供“清除模板缓存”按钮,解决国内大流量门户网站性能瓶颈
- 合规审计:在 layouts 里统一插入公安备案号组件 <%= partial("compliance/beian.plush.html") %>,保证所有页面自动携带备案信息,避免人工遗漏