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

如何使用templ实现类似EJS的模板布局包裹功能?

在templ中实现布局包裹页面(替代EJS的layout功能)

完全可行,templ本身支持通过组件参数传递实现类似EJS的布局包裹模式,比EJS写法更类型安全,还能灵活扩展。

第一步:改造你的Boilerplate.templ

把原来固定嵌入Body的写法,改成接受一个templ.Component类型的参数,用来渲染页面内容:

package components

// 定义布局组件,接受页面内容作为参数
templ Boilerplate(content templ.Component) {
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>My App</title>
    <!-- 这里可以放全局样式、脚本、meta标签等 -->
  </head>
  <body>
    <!-- 渲染传入的页面内容 -->
    @content
  </body>
  </html>
}

第二步:在页面模板中使用布局

你可以直接在页面里把内容传给Boilerplate,或者把页面内容抽成单独组件再传入,两种方式都适用:

方式1:直接传内容

package pages

import "your-project/components"

templ Home() {
  @components.Boilerplate(
    // 直接在参数中编写页面内容
    templ.Component(func(ctx context.Context, w io.Writer) error {
      <h1>首页</h1>
      <p>这是被Boilerplate布局包裹的首页内容</p>
      return nil
    }),
  )
}

方式2:抽成单独组件(结构更清晰)

package pages

import "your-project/components"

// 单独定义页面内容组件
templ HomeContent() {
  <h1>首页</h1>
  <p>这是被Boilerplate布局包裹的首页内容</p>
}

// 用布局包裹内容组件
templ Home() {
  @components.Boilerplate(HomeContent())
}

进阶:给布局添加自定义参数

如果需要每个页面自定义标题、脚本等,还能给Boilerplate加额外参数,比如:

package components

// 新增title参数,支持页面自定义标题
templ Boilerplate(pageTitle string, content templ.Component) {
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title><%= pageTitle %></title>
  </head>
  <body>
    @content
  </body>
  </html>
}

页面调用时传入标题:

templ Home() {
  @components.Boilerplate("首页 - 我的应用", HomeContent())
}

这种方式完全替代EJS的<% layout('layouts/boilerplate') -%>功能,而且templ会在编译时检查组件类型和参数,避免运行时错误,更贴合Go的类型安全特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:02:37