我用卡片笔记法记录笔记,攒了上千条笔记后,我想在 Frontmatter 中添加一个字段反映每个笔记的权重,便于在数据库中排序和查看。
所以我引入了【编辑次数】和【编辑日期】字段,并设置了一个 Templater 脚本,实现按下快捷键或文件变更后自动更新这两个字段。
具体逻辑为:
- 如果该文件的【编辑日期】是今天,那么【编辑次数】保持不变;
- 如果【编辑日期】不是今天,那么【编辑次数】+1。
脚本如下。
一、通过快捷键使用的版本
module.exports = async (tp) => {
const KEY_EDIT_COUNT = "编辑次数";
const KEY_LAST_EDIT = "编辑日期";
const app = tp.app;
const file = app.workspace.getActiveFile();
if (!file) return;
// 从 metadataCache 读取 frontmatter
const cache = app.metadataCache.getFileCache(file);
const fm = cache?.frontmatter ?? {};
const old_count = fm[KEY_EDIT_COUNT] ?? 0;
const new_edit = tp.date.now("YYYY-MM-DD");
const last_edit = fm[KEY_LAST_EDIT] ?? tp.file.last_modified_date("YYYY-MM-DD");
if (new_edit === last_edit && old_count != 0) return;
const new_count = (parseInt(old_count) || 0) + 1;
// 使用官方 API 修改 frontmatter
await app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter[KEY_EDIT_COUNT] = new_count;
frontmatter[KEY_LAST_EDIT] = new_edit;
});
new Notice(`编辑次数已更新:${new_count}`);
};
二、自动检测运行的脚本
// update-edit-count-official.js
// 使用 Obsidian 官方 FrontMatter API 的版本
// 要求 Obsidian 1.3+ (含 FrontMatterInfo API)
module.exports = async (tp) => {
const KEY_EDIT_COUNT = "编辑次数";
const KEY_LAST_EDIT = "编辑日期";
const app = tp.app;
app.vault.on("modify", async (file) => {
if (!file || file.extension !== "md") return;
// 从 metadataCache 读取 frontmatter
const cache = app.metadataCache.getFileCache(file);
const fm = cache?.frontmatter ?? {};
const old_count = fm[KEY_EDIT_COUNT] ?? 0;
const new_edit = tp.date.now("YYYY-MM-DD");
const last_edit = fm[KEY_LAST_EDIT] ?? tp.file.last_modified_date("YYYY-MM-DD");
if (new_edit === last_edit && old_count != 0) return;
const new_count = (parseInt(old_count) || 0) + 1;
// 使用官方 API 修改 frontmatter
await app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter[KEY_EDIT_COUNT] = new_count;
frontmatter[KEY_LAST_EDIT] = new_edit;
});
});
};