File

檔案資訊

預設情況下,並非所有頁面都由文件支持,包括頂層 section 頁面、taxonomy 頁面和 term 頁面。若無文件支持,則無法檢索檔案資訊。

要為上述頁面提供文件支持,請在對應目錄下創建一個 _index.md 文件。例如:

content/
└── books/
    ├── _index.md  <-- 頂層區段頁面
    ├── book-1.md
    └── book-2.md

方法

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
ContentBaseName a b
Dir news/ news/b/
Ext md md
Filename /home/user/… /home/user/…
IsContentAdapter false false
LogicalName a.en.md index.en.md
Path news/a.en.md news/b/index.en.md
Section news news
TranslationBaseName a index
UniqueID 15be14b… 186868f…

防禦性編程

某些頁面可能不會由檔案支持。例如:

  • 頂層區段頁面
  • 分類頁面
  • 術語頁面

在沒有文件支持的情況下,Hugo 在嘗試訪問 .File 屬性時會報錯。為了進行防禦性編程,首先檢查文件是否存在:

{{ with .File }}
  {{ .ContentBaseName }}
{{ end }}