経緯
Templater において、テンプレートをもとに新しいページを作りたいときがあります。
Create new note from template
で作成するやつです。
ここで、作成するページに対して、特定のキーワード候補で type
属性の Frontmatter を設定したくなった。
というのも Frontmatter を設定するときに type: {Fleeting, Literature, ...}
を手動で設定すると表記揺れが発生してしまうのでは…? という懸念があったためです。
それら type ごとにテンプレートを作成してもよいですが、ほぼ同じ内容のテンプレートを増やしたくはありません。
どうやったか
url: https://silentvoid13.github.io/Templater/user-functions/script-user-functions.html
title: "User Scripts - Templater"
host: silentvoid13.github.io
favicon: ../favicon.svg
特定のキーワードを選択するユーザスクリプトを Templater & AI で作りました。
99_Templater/Scripts/selectMultipleOptions.js に下記の js 関数を実装します。
なお、tp
を引数として渡さないと templater の tp をユーザ関数は認識してくれないことに注意します。
async function selectMultipleOptions(tp, options) {
const finishOption = "Finish!!";
const selectedOptions = [];
let remainingOptions = [...options];
while (remainingOptions.length > 0) {
const candidateOptions = [...remainingOptions, finishOption];
const selectedOption = await tp.system.suggester(candidateOptions, candidateOptions);
if (selectedOption === finishOption || selectedOption === null) break;
selectedOptions.push(selectedOption);
remainingOptions = remainingOptions.filter(option => option !== selectedOption);
}
if (selectedOptions.length === 0) return "";
return "\n - " + selectedOptions.join("\n - ");
}
module.exports = selectMultipleOptions;
あとはテンプレート側を以下のように実装します。
tp.user.selectMultipleOptions(tp, [...])
で複数選択が行えます。
---
title: Template_Note
permalink:
type: <% await tp.user.selectMultipleOptions(tp, ["Fleeting", "Literature", "Permanent"]) %>
tags:
refs:
date: <% tp.date.now("YYYY-MM-DD hh:mm:ss") %>
updated: <% tp.date.now("YYYY-MM-DD hh:mm:ss") %>
draft: false
---
<%*
const targetFolder = "01_Note";
const currentFilePath = tp.file.path(true);
const targetPath = `${targetFolder}/${tp.file.title}`;
if (!currentFilePath.startsWith(targetFolder + "/")) {
await tp.file.move(targetPath);
}
%>
Templater の設定ファイルで下記のように設定しないといけないことに注意しましょう。