菜单

8.1.20250720 不同标签的编码逻辑

#编码 #数字花园 #templater

修改编码的逻辑,根据不同的标签,编码的逻辑不一样。比如

  • 人物或者角色,3开头
  • 企业:1开头
  • 思维模型:2开头
  • 城市或者地名:4开头
  • app:5开头
  • 书名
  • 行业:前面两位为3.1

代码实现了一个隐射表,方便自己配置,非常强大。


/* setTitleFromFilename.js */
async function setTitleFromFilename() {
  const file = app.workspace.getActiveFile();
  if (!file) return;

  /* ========== 1. 读取并标准化标签 ========== */
  const cache = app.metadataCache.getFileCache(file);
  const rawTags = cache?.frontmatter?.tags ?? cache?.frontmatter?.tag ?? [];
  const tags = Array.isArray(rawTags)
    ? rawTags.map(t => String(t).toLowerCase())
    : [String(rawTags).toLowerCase()];

  /* ========== 2. 标签 → 前缀 映射表(按优先级排序) ========== */
  const tagRules = [
    { match: ['人物', '角色'], prefix: '3.1' },
    { match: ['企业'],        prefix: '1.1' },
    { match: ['思维模型'],    prefix: '2.1' },
    { match: ['城市', '地名'], prefix: '4.1' },
    { match: ['app'],         prefix: '5.1' },
    { match: ['书名'],        prefix: '6.1' },
    { match: ['行业'],        prefix: '1.0' }   // 两位:1.0
  ];

  /* ========== 3. 根据标签确定前缀 ========== */
  let prefixBase = '8.1';          // 默认兜底
  for (const rule of tagRules) {
    if (rule.match.some(k => tags.includes(k))) {
      prefixBase = rule.prefix;
      break;                       // 命中即停
    }
  }

  /* ========== 4. 拼完整前缀:基础 + 年月日 ========== */
  const today = new Date();
  const y = today.getFullYear();
  const m = String(today.getMonth() + 1).padStart(2, '0');
  const d = String(today.getDate()).padStart(2, '0');
  const datePart = `${y}${m}${d}`;
  const datePrefix = `${prefixBase}.${datePart}`;

  /* ========== 5. 处理 title ========== */
  const currentTitle = cache?.frontmatter?.title;
  let newTitle;
  if (!currentTitle) {
    newTitle = `${datePrefix} ${file.basename}`;
  } else if (String(currentTitle).trim().startsWith('000')) {
    const cleanTitle = String(currentTitle).trim().replace(/^000\s*/, '');
    newTitle = `${datePrefix} ${cleanTitle}`;
  } else if (!/^\d/.test(String(currentTitle).trim())) {
    newTitle = `${datePrefix} ${String(currentTitle).trim()}`;
  } else {
    new Notice('title 已符合规则,未变动');
    return;
  }

  await app.fileManager.processFrontMatter(file, fm => {
    fm.title = newTitle;
  });
  new Notice(`✅ title 已设为:${newTitle}`);
}

module.exports = setTitleFromFilename;

#编码

ob地址:笔记