菜单

模板

相关源文件

Templates 系统使用 Go 的 text/template 引擎,为 HTTP 响应提供服务器端模板处理。此中间件将响应体作为模板执行,提供丰富的内置函数、自定义函数支持以及与 Caddy 的 HTTP 请求处理流程集成。

有关不进行模板处理的静态文件服务,请参阅 静态文件服务器。有关内容转换和编码,请参阅 内容编码

架构概述

Templates 系统作为一个 HTTP 中间件运行,它会拦截响应并在将响应发送给客户端之前将其作为 Go 模板进行处理。

模板处理组件

来源: modules/caddyhttp/templates/templates.go327-348 modules/caddyhttp/templates/tplcontext.go48-58 modules/caddyhttp/templates/frontmatter.go13-79

配置

The Templates 结构配置了模板处理行为

字段类型描述默认
FileRoot字符串文件系统访问的根路径{http.vars.root}
MIMETypes[]string要作为模板处理的 MIME 类型["text/html", "text/plain", "text/markdown"]
Delimiters[]string模板操作定界符["{{", "}}"]
ExtensionsRawcaddy.ModuleMap自定义函数扩展-

中间件仅处理 MIME 类型匹配的响应,具体由 templates.go399-407 中的 shouldBuf 函数确定。

来源: modules/caddyhttp/templates/templates.go327-348 modules/caddyhttp/templates/templates.go375-381 modules/caddyhttp/templates/templates.go486-490

模板执行流程

模板处理遵循从 HTTP 响应到渲染输出的特定流程

核心执行发生在 executeTemplate 中,templates.go437-463,它创建一个 TemplateContext 并通过 executeTemplateInBuffer tplcontext.go240-251 处理缓冲的响应。

来源: modules/caddyhttp/templates/templates.go392-434 modules/caddyhttp/templates/templates.go437-463 modules/caddyhttp/templates/tplcontext.go240-251

模板上下文和函数

The TemplateContext 提供了模板的执行环境,允许访问请求数据、文件系统以及丰富的内置函数

上下文结构

字段类型目的
根目录http.FileSystem文件系统访问
Req*http.Request当前的 HTTP 请求
Args[]any来自 include 调用的参数
RespHeaderWrappedHeader响应头操作
CustomFuncs[]template.FuncMap插件提供的函数

内置函数

文件操作

内容处理

HTTP 操作

请求/响应访问

来源: modules/caddyhttp/templates/tplcontext.go62-98 modules/caddyhttp/templates/tplcontext.go112-467 modules/caddyhttp/templates/tplcontext.go270-312

前端主题支持

该系统支持以多种格式从文档头中提取结构化元数据

前端主题解析由 extractFrontMatter 处理 frontmatter.go13-78 和特定格式的解析器

splitFrontMatter 模板函数返回一个 parsedMarkdownDoc 结构体,其中包含分离的元数据和正文内容。

来源: modules/caddyhttp/templates/frontmatter.go13-78 modules/caddyhttp/templates/frontmatter.go81-98 modules/caddyhttp/templates/frontmatter.go112-128

自定义函数扩展

模板系统支持通过 CustomFunctions 接口自定义函数

自定义函数在配置时加载 templates.go367-373 并通过 maybe 函数提供 tplcontext.go520-549,它安全地调用可能在所有部署中都不可用的可选函数。

扩展系统允许插件在 http.handlers.templates.functions.* 命名空间下注册并提供额外的模板功能。

来源: modules/caddyhttp/templates/templates.go350-354 modules/caddyhttp/templates/templates.go367-373 tplcontext.go520-549

与 HTTP 管道集成

模板作为中间件处理程序集成到 Caddy 的 HTTP 处理中

中间件使用 caddyhttp.NewResponseRecorder 根据 MIME 类型有条件地缓冲响应 templates.go409 它会移除模板处理后使之失效的某些头

  • Accept-Ranges - 动态内容不支持范围
  • Last-Modified - 动态内容总是变化的
  • Etag - 无法为动态内容生成有意义的 Etag
  • Content-Length - 处理后重新计算

通过 httpInclude 进行的虚拟请求使用 virtualResponseWriter templates.go468-484 以防止与 Caddy-Templates-Include 头发生递归 tplcontext.go589

来源: modules/caddyhttp/templates/templates.go392-434 modules/caddyhttp/templates/templates.go424-432 modules/caddyhttp/templates/templates.go468-484 modules/caddyhttp/templates/tplcontext.go177-201