File
对于有文件支持的页面,返回给定页面的文件信息。
Syntax
PAGE.File
Returns
hugolib.fileInfo
默认情况下,并非所有页面都有文件支持,包括顶层 栏目页面、分类法页面 和 术语页面。根据定义,当文件不存在时,您无法检索文件信息。
要为上述页面之一提供文件支持,请在相应目录中创建 _index.md 文件。例如:
content/
└── books/
├── _index.md <-- 顶层栏目页面
├── book-1.md
└── book-2.md通过如下示例中所示验证文件存在性来防御性编码。
方法
Path、Dir 和 Filename 中的路径分隔符(斜杠或反斜杠)取决于操作系统。
BaseFileName
(string) 文件名,不包括扩展名。
{{ with .File }}
{{ .BaseFileName }}
{{ end }}ContentBaseName
(string) 如果页面是分支或叶捆绑包,则为包含目录的名称,否则为 TranslationBaseName。
{{ with .File }}
{{ .ContentBaseName }}
{{ end }}Dir
(string) 文件路径,不包括文件名,相对于 content 目录。
{{ with .File }}
{{ .Dir }}
{{ end }}Ext
(string) 文件扩展名。
{{ with .File }}
{{ .Ext }}
{{ end }}Filename
(string) 绝对文件路径。
{{ with .File }}
{{ .Filename }}
{{ end }}IsContentAdapter
New in v0.126.0(bool) 报告文件是否为 内容适配器。
{{ with .File }}
{{ .IsContentAdapter }}
{{ end }}LogicalName
(string) 文件名。
{{ with .File }}
{{ .LogicalName }}
{{ end }}Path
(string) 文件路径,相对于 content 目录。
{{ with .File }}
{{ .Path }}
{{ end }}Section
(string) 文件所在顶层栏目的名称。
{{ with .File }}
{{ .Section }}
{{ end }}TranslationBaseName
(string) 文件名,不包括扩展名和语言标识符。
{{ with .File }}
{{ .TranslationBaseName }}
{{ end }}UniqueID
(string) .File.Path 的 MD5 哈希值。
{{ with .File }}
{{ .UniqueID }}
{{ end }}示例
考虑多语言项目中的此内容结构:
content/
├── news/
│ ├── b/
│ │ ├── index.de.md <-- 叶捆绑包
│ │ └── index.en.md <-- 叶捆绑包
│ ├── a.de.md <-- 常规内容
│ ├── a.en.md <-- 常规内容
│ ├── _index.de.md <-- 分支捆绑包
│ └── _index.en.md <-- 分支捆绑包
├── _index.de.md
└── _index.en.md使用英语语言站点:
| 常规内容 | 叶捆绑包 | 分支捆绑包 | |
|---|---|---|---|
| BaseFileName | a.en | index.en | _index.en |
| ContentBaseName | a | b | news |
| Dir | news/ | news/b/ | news/ |
| Ext | md | md | md |
| Filename | /home/user/… | /home/user/… | /home/user/… |
| IsContentAdapter | false | false | false |
| LogicalName | a.en.md | index.en.md | _index.en.md |
| Path | news/a.en.md | news/b/index.en.md | news/_index.en.md |
| Section | news | news | news |
| TranslationBaseName | a | index | _index |
| UniqueID | 15be14b… | 186868f… | 7d9159d… |
防御性编码
站点上的某些页面可能没有文件支持。例如:
- 顶层栏目页面
- 分类法页面
- 术语页面
没有支持文件,如果您尝试访问 .File 属性,Hugo 将抛出错误。要防御性编码,首先检查文件存在性:
{{ with .File }}
{{ .ContentBaseName }}
{{ end }}