将hugo日期输出为中文

一直觉得中文竖排别有一番风情,尤其是各色法贴碑刻,无不沁人心脾。

蜀素帖
蜀素帖

其实,本站素来有坚排模式,盖因嫌细微的缺陷未改进,迟迟未启用,仅余存了辛德勇老师的孤篇《賣書人徐元勳》作为样张。

其中让我心存芥蒂的一个细节是,坚排模式下,Hugo输出的日期仍是阿拉伯数字,视觉上极尴尬。

今天,无意看到hugo的一个Data Templates功能 。大呼救星来也。

The data folder is where you can store additional data for Hugo to use when generating your site. Data files aren’t used to generate standalone pages; rather, they’re meant to be supplemental to content files. This feature can extend the content in case your front matter fields grow out of control. Or perhaps you want to show a larger dataset in a template (see example below). In both cases, it’s a good idea to outsource the data in their own files.

These files must be YAML, JSON, or TOML files (using the .yml, .yaml, .json, or .toml extension). The data will be accessible as a map in the .Site.Data variable.

所以在根目录的Data目录下新建一个名为chinese_date.json的数据文件(官方声明支持yaml、yml、toml、json格式),输入如下内容:

{
  "year":
   { "2010": "二〇一一年",
     "2012": "二〇一二年",
     "2013": "二〇一三年",
     "2014": "二〇一四年",
     "2015": "二〇一五年",
     "2016": "二〇一六年",
     "2017": "二〇一七年",
     "2018": "二〇一八年",
     "2019": "二〇一九年",
     "2020": "二〇二〇年",
     "2021": "二〇二一年",
     "2022": "二〇二二年",
     "2023": "二〇二三年",
     "2024": "二〇二四年",
     "2025": "二〇二五年"},

  "month":
   { "1": "一月",
     "2": "二月",
     "3": "三月",
     "4": "四月",
     "5": "五月",
     "6": "六月",
     "7": "七月",
     "8": "八月",
     "9": "九月",
     "10": "十月",
     "11": "十一月",
     "12": "十二月" },

  "day":
   { "1": "一日",
     "2": "二日",
     "3": "三日",
     "4": "四日",
     "5": "五日",
     "6": "六日",
     "7": "七日",
     "8": "八日",
     "9": "九日",
     "10": "十日",
     "11": "十一日",
     "12": "十二日",
     "13": "十三日",
     "14": "十四日",
     "15": "十五日",
     "16": "十六日",
     "17": "十七日",
     "18": "十八日",
     "19": "十九日",
     "20": "二十日",
     "21": "二十一日",
     "22": "二十二日",
     "23": "二十三日",
     "24": "二十四日",
     "25": "二十五日",
     "26": "二十六日",
     "27": "二十七日",
     "28": "二十八日",
     "29": "二十九日",
     "30": "三十日",
     "31": "三十一日" }
}

然后,在layouts/partials/目录下新建date.html,内容为:

{{ index $.Site.Data.chinese_date.year (printf "%d" .Date.Year) }}
{{ index $.Site.Data.chinese_date.month (printf "%d" .Date.Month) }}
{{ index $.Site.Data.chinese_date.day (printf "%d" .Date.Day) }}

在主题对应的单页模板(如single.html或post.html)中替代日期部分即可:

{{ partial "date.html"  . }}

实际效果可前往驻足:

賣書人徐元勳

如此,倘若有闲心的话,完全可以整一个天干地支纪年出来。