为博客设置归档
👉🏻 归档
将笔记和随笔文章放在 Notes 和 Posts 文件夹,然后用 Dataview 遍历,分组渲染出来。
用 ChatGPT 几分钟就生成并修改好了,以下是 Dataview 代码:
// Helper function to format date
function formatDate(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const day = String(date.getDate()).padStart(2, '0');
return { year, month, day, formatted: `${day}日` };
}
// Initialize a structure to hold grouped data and counts
const groupedData = {};
const yearlyCounts = {};
// Retrieve and sort pages
const pages = dv.pages('"Notes" or "Posts"').filter((page) => page["dg-publish"]).sort(p => p.file.ctime, 'desc');
// Group pages by year and month
pages.forEach(p => {
const { year, month, formatted } = formatDate(p.file.ctime);
if (!groupedData[year]) {
groupedData[year] = {};
yearlyCounts[year] = 0; // Initialize yearly count
}
if (!groupedData[year][month]) {
groupedData[year][month] = [];
}
// Create a string that includes the date and file link
const entry = `${formatted} ${dv.fileLink(p.file.path)}`;
groupedData[year][month].push(entry);
yearlyCounts[year]++; // Increment count for the year
});
// Render the grouped data
for (const year in groupedData) {
// Display year with count
dv.header(2, `${year}年 (${yearlyCounts[year]})`);
for (const month in groupedData[year]) {
dv.header(3, `${month}月`); // Month as a level 3 header
dv.list(groupedData[year][month]);
}
}