Templater allows for user functions to be defined, and this is a perfect candidate for a user function. See User Scripts - Templater for the original documentation.
First you need to dedicate a folder for these user functions, and set which folder you chose in Settings > Templater (User Script Functions) > Script files folder location.
Within this folder you create one file for each user function, so say we aim to create chooseColor
, you would create the file chooseColor.js
(not it has to have the .js
extension, and not .md
(or .js.md
). This means in most cases, that you need to edit this file outside of Obsidian.
The contents of this file needs to follow a given format for it to be recognised as a user function, but it’s not that hard, so if I copy-paste your code we end up with:
async function chooseColor() {
const colors = [
'orange',
'yellow', 'yyellow',
'gray',
'blue','bblue','cyan',
'green', 'ggreen', 'sqlgreen', 'comment',
'red', 'rred', 'sqlred',
'purple', 'ppurple'
'pink', 'ppink', 'sqlpink',
'vsaction', 'vshelper', 'vspink',
'gold', 'silver', 'litesilver',
'brown'];
return await tp.system.suggester(colors, colors, false, 'Color');
}
module.exports = chooseColor;
Note that after you’ve defined it, and refreshed Obsidian’s/Templater’s look of user function, should include your newly defined function in a list under the script folder mentioned earlier.
Now your Template #1 could look like:
<%*
const color = await tp.user.chooseColor();
if ( color !== null ) {
tR += `<span class="fs8 ${color}">${ tp.file.cursor() }</span>`;
}
-%>
Caveat: If your user function has compiler errors, it’ll hinder all templates from being executed, so if you get some strange error messages in the Console (of Developer Tools), verify that you don’t have any issues in either of your user functions. (This is most likely a case, just when you’re developing your user functions.