templates
将响应体作为模板文档执行。模板提供了用于创建简单动态页面的功能原语。功能包括 HTTP 子请求、HTML 文件包含、Markdown 渲染、JSON 解析、基本数据结构、随机性、时间等。
语法
templates [<matcher>] {
mime <types...>
between <open_delim> <close_delim>
root <path>
}
-
mime 是模板中间件将处理的 MIME 类型;任何不具有限定
Content-Type
的响应都不会被评估为模板。默认值:
text/html text/plain
。 -
between 是模板操作的开闭分隔符。如果它们与文档的其余部分发生冲突,您可以更改它们。
默认值:
{{ }}
。 -
root 是站点根目录,在使用访问文件系统的函数时使用。
默认为
root
指令设置的站点根目录,如果未设置则为当前工作目录。
内置模板函数的文档可以在模板模块中找到。
示例
要查看使用模板提供 markdown 的完整示例站点,请查看本网站的源代码!具体来说,请查看 Caddyfile
和 src/docs/index.html
。
为静态站点启用模板:
example.com {
root * /srv
templates
file_server
}
要使用模板提供简单的静态响应,请确保设置 Content-Type
:
example.com {
header Content-Type text/plain
templates
respond `当前年份是:{{now | date "2006"}}`
}