옵시디언 활용/Templater

Templater 심화: Hooks Module (tp.hooks)

반응형

Templater 플러그인의 Hooks 모듈은 Obsidian에서 템플릿이 실행될 때 특정 코드를 자동으로 실행할 수 있는 기능을 제공합니다. 이는 사용자가 자동화를 구성하고, 템플릿의 실행 결과에 따라 추가 작업을 진행할 수 있도록 해줍니다.

tp.hooks.on_all_templates_executed

tp.hooks.on_all_templates_executed 함수는 모든 활성 템플릿의 실행이 완료될 때 호출되어야 하는 콜백 함수를 등록합니다. 여기서 "활성 템플릿"이란 현재 실행 중인 템플릿을 의미하며, tp.file.includetp.file.create_new과 같은 명령을 사용하여 여러 템플릿을 실행하는 경우에도 적용됩니다.

매개변수

  • callback_function: 모든 활성 템플릿의 실행이 완료되었을 때 실행될 콜백 함수입니다.

특징

  • 병렬 실행 지원: tp.hooks.on_all_templates_executed를 여러 번 호출하면, 등록된 모든 콜백 함수들이 병렬로 실행됩니다. 이는 템플릿의 후처리 작업을 동시에 여러 개 진행할 수 있게 해줍니다.

사용 예제

프론트매터 업데이트

<%* 
tp.hooks.on_all_templates_executed(async () => { const file = tp.file.find_tfile(tp.file.path(true)); 
await app.fileManager.processFrontMatter(file, (frontmatter) => { frontmatter["key"] = "value"; }); }); 
%>

템플릿의 실행이 모두 완료된 후, 현재 파일의 프론트매터를 찾아서 새로운 키-값 쌍을 추가합니다.

다른 플러그인의 명령 실행

<%* 
tp.hooks.on_all_templates_executed(() => { app.commands.executeCommandById("obsidian-linter:lint-file"); }); 
-%>

Templater가 파일을 업데이트한 후, Linter 플러그인을 통해 현재 파일에 대한 lint 과정을 자동으로 실행합니다.

데일리 노트 생성 후 날짜 기반으로 태그 추가하기

<%*
tp.hooks.on_all_templates_executed(async () => {
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const dateTag = `#${year}/${month}/${day}`;

  const file = tp.file.find_tfile(tp.file.path(true));
  await app.fileManager.append(file, `\n\n${dateTag}`);
});
%>

데일리 노트를 생성한 후, 해당 파일에 현재 날짜를 기반으로 태그를 자동으로 추가합니다. (#YYYY/MM/DD 형식)

특정 파일에 로그 남기기

<%*
tp.hooks.on_all_templates_executed(async () => {
  const logFilePath = "/Logs/TemplaterLog.md";
  const timestamp = new Date().toLocaleString();
  const logEntry = `템플릿 실행됨: ${timestamp}\n`;

  const logFile = tp.file.find_tfile(logFilePath);
  if (logFile) {
    await app.fileManager.append(logFile, logEntry);
  } else {
    await app.fileManager.createFile(logFilePath, logEntry);
  }
});
%>

템플릿이 실행될 때마다 이를 Logs/TemplaterLog.md파일에 로그로 기록합니다.

특정 태그가 있는 노트 목록 업데이트

<%*
tp.hooks.on_all_templates_executed(async () => {
  const tag = "#project";
  const notes = app.vault.getMarkdownFiles().filter(file => 
    file.contains(tag)
  );

  const list = notes.map(file => `- [[${file.basename}]]`).join('\n');
  await tp.file.append(list);
});
%>

특정 태그(#project)를 포함하는 모든 마크다운 파일을 찾아 그 목록을 현재 편집 중인 파일의 끝에 추가합니다.


 

반응형