v2中文文档
项目

templates

将响应体作为template文件执行。模板提供了制作简单动态页面的功能基元。功能包括HTTP子请求、HTML文件包含、Markdown渲染、JSON解析、基本数据结构、随机性、时间等。

语法

templates [<matcher>] {
	mime    <types...>
	between <open_delim> <close_delim>
	root    <path>
	extensions {
		<name> {
			...
		}
	}
}
  • mime 是模板中间件会处理的MIME类型;任何不具备合格Content-Type的响应都不会被作为模板求值。

    默认:text/html text/plain

  • between 是模板动作的开始和结束定界符。如果它们与文档其他部分冲突,你可以更改它们。

    默认:{{ }}

  • root 是使用访问文件系统的函数时的站点根目录。

    默认为root指令设置的站点根目录;如果未设置,则为当前工作目录。

  • extensions 允许你注册由http.handlers.templates.functions.*命名空间中的模块提供的自定义模板函数。

    块内的每个子指令都对应一个模块名称。这些模块可以向模板函数映射添加自定义函数,通常用于实现可复用组件。此功能主要面向插件。

内置模板函数的文档可在templates模块中找到。

示例

关于使用模板提供markdown服务的完整站点示例,请查看这个网站的源代码!具体来说,请查看Caddyfilesrc/docs/index.html

为静态站点启用模板:

example.com {
	root /srv
	templates
	file_server
}

要使用模板提供简单的静态响应,请确保设置Content-Type

example.com {
	header Content-Type text/plain
	templates
	respond `Current year is: {{now | date "2006"}}`
}

使用模板扩展(插件):

example.com {
	root /srv
	templates {
		extensions {
			# 需要 caddy-hitcounter 插件:
			# https://github.com/mholt/caddy-hitcounter
			hitCounter {
				style bright_green
				pad_digits 6
			}
		}
	}
	file_server
}