获取包含当前 FreeMarker 的目录的绝对路径

Get absolute path to directory containing current FreeMarker

Apache FreeMarker中,如何获取包含当前.ftl文件的目录的绝对路径?

例如,如果我正在处理文件 /path/to/template.ftl,那么我正在寻找一种方法将 /path/to 放入 /path/to/template.ftl

我试过 .current_template_name and friends, but these really only contain the name of the file, not its absolute path (from which I could get the parent directory). I've also tried absolute_template_name,但这似乎只是在名称前加上 / 使路径看起来是绝对路径,但它并没有解析为真实路径绝对路径。

背景:我正在使用 Freemarker 模板化 Asciidoc 文件,并且 Asciidoc 文件必须包含位于 .flt 文件原始目录下的其他 Asciidoc 文件,因此不能相对于临时“扩展”了 Asciidoc 文件。

模板使用的模板路径始终是虚拟的,并由 Configuration 中设置的 TemplateLoader 对象解析。 TemplateLoader 只是一个接口,有多种实现,所以是 FreeMarker 的黑盒。模板的实际位置可以在jar文件中,甚至在数据库中table,所以一般来说模板在文件系统上是没有路径的

通常,您设置 TemplateLoader 以便它可以访问您需要的所有模板。那你什么技巧都不需要,直接用模板路径就可以了。

另一种可能性是使用 FileTemplateLoader 将根目录用作基本目录。对于大多数应用程序(尤其是网络应用程序,出于安全原因)来说,这当然不是一个好主意。