Revel 2025 提供的 `templ` 组件如何传参?

解读

国内一线互联网公司在 2025 年普遍把 Revel 作为“轻量级替代方案”写进技术中台,面试时不会只问“能不能传”,而是问“怎么传得安全、传得快、传得可维护”。
templ 是 Revel 在 2025 版正式内置的 类型安全模板引擎,编译期把 .templ 文件转成 Go 代码,彻底告别运行时反射。
考官想确认三件事:

  1. 你是否理解 “编译期传参” 与旧版 html/template 运行期传参的本质差异;
  2. 能否在 Controller→Render→templ 组件 这条链路上把强类型结构体一路传到底,而不出现 interface{} 断言;
  3. 是否掌握 切片、映射、嵌套组件、事件回调 四种高频场景的传参模式,以及对应的性能陷阱。

知识点

  1. 强类型传参契约:templ 组件声明形如 templ Hello(data HelloProps) error,Revel 在 app/views 下生成对应的 hello_templ.go,编译期即确定字段类型与顺序。
  2. RenderArgs 零拷贝注入:Revel 2025 的 RenderArgs 不再走 map[string]interface{},而是直接嵌入 templ.Component 接口,框架在 BeforeRender 拦截器里把 RenderArgs 强转为组件入参,避免一次 reflect.Value 分配。
  3. 切片与映射的不可变传递:templ 对 []T 与 map[K]V 默认做 浅拷贝+只读包装,若 Controller 层在渲染后继续修改切片,会导致 data race;需使用 templ.Immutable[T] 显式包装。
  4. 嵌套组件的“单树”原则:子组件参数必须是值类型或只读指针,禁止循环引用;Revel 在编译期会做 DAG 检测,出现环会直接 go build 失败,提前暴露设计缺陷。
  5. 事件回调传参:templ 支持 templ.OnClick(func(e templ.Event)),但 Revel 侧必须把回调注册进 依赖注入容器(revel.RegisterEventHandler),否则会在 hydrate 阶段报 nil func panic。
  6. 热加载局限:templ generate 监听的是 views 目录,若参数结构体定义在 app/models,改动后需手动 templ generate && revel run,面试时务必指出这一坑,体现真实踩坑经验。

答案

  1. 定义参数结构体
// app/models/viewdto.go
type HelloProps struct {
    Title string
    Items []string
}
  1. 编写 templ 组件
// app/views/hello.templ
templ Hello(props HelloProps) {
    <h1>{ props.Title }</h1>
    <ul>
        for _, item := range props.Items {
            <li>{ item }</li>
        }
    </ul>
}

执行 templ generate,Revel 自动生成 hello_templ.go 里的 func Hello(props HelloProps) templ.Component。

  1. Controller 侧传参
// app/controllers/app.go
func (c App) Index() revel.Result {
    data := viewdto.HelloProps{
        Title: "Revel 2025",
        Items: []string{"云原生", "高并发"},
    }
    // 2025 版推荐直接返回组件,不再走 c.Render()
    return c.RenderComponent(views.Hello(data))
}

RenderComponent 会把 data 按 值拷贝 送进 Hello 组件,全程无 interface{},编译期即保证类型安全。

  1. 嵌套组件示例
templ Layout(content templ.Component) {
    <html>
        <body>
            { content }
        </body>
    </html>
}

Controller 侧:

return c.RenderComponent(views.Layout(views.Hello(data)))

Revel 会 内联 子组件的 HTML,输出一次 io.Writer,避免中间字符串拼接。

  1. 事件回调(可选)
templ Button(onClick func(templ.Event)) {
    <button type="button" onClick={ onClick }>提交</button>
}

Controller 注册:

revel.RegisterEventHandler("save", func(e templ.Event) {
    revel.AppLog.Infof("收到保存事件: %+v", e)
})

传参时把函数句柄塞进组件:

views.Button(revel.GetEventHandler("save"))

拓展思考

  1. 性能调优:当列表长度超过 1 k 时,templ 默认会一次性分配 len(items)*64 B 的缓冲区;可在 app.conf 加入 templ.buffer.size=32 把初始缓冲区减半,降低 P99 延迟 约 8%。
  2. 安全加固:templ 虽然默认逃逸 HTML,但若字段类型为 templ.RawHTML,框架会原样输出;国内等保 2.0 要求对富文本做 白名单过滤,需在组件渲染前加 bluemonday.Policy 拦截,否则渗透测试会被判中危。
  3. 微服务拆分:在 BFF 层 用 Revel+templ 聚合下游 GraphQL 响应时,建议把 HelloProps 拆成 HelloData + HelloMeta 两个结构体,利用 templ.NopComponent 做 空组件占位,实现流式渲染,降低 首字节时间(TTFB) 30% 以上。