How to Use Templater JS Scripts

Summary

Notes

Step 1: Write .js file

async function notice(tp) {
    const text = await tp.system.prompt("What's Good?")
    new Notice(text, 5000)
}

module.exports = notice

Step 2: Write the Templater command
<%* tp.user.notice(tp) %>

A note on file names

it appears that Templater uses the name of the JS file and not the function name when you call the user command. I suggest naming the file the same as your exported function to avoid confusion.

Step 3: Run your new Command
Create a new note with the "Notice" template. The script prompts for input and a notification pops up with what you typed.

Breaking it down

The JS file

The Templater Command

Advanced Usage

<%*
let cmEditorAct = this.app.workspace.activeLeaf.view.sourceMode.cmEditor;
let curLine = cmEditorAct.getCursor().line;
cmEditorAct.setSelection({ line: curLine, ch: 0 }, { line: curLine, ch: 9999 });

function createBlockHash() {
	let result = '';
	var characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for ( var i = 0; i < 7; i++ ) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result;
}

let id = createBlockHash();
let block = ![[${tp.file.title}#^${id}]].split("\n").join("");
navigator.clipboard.writeText(block).then(text => text);
tR = tp.file.selection() + ^${id}.split("\n").join("");
%>
function addBlockRef(tp) {
    
	//Use the Obsidian API to get the CodeMirror Editor
    const editor = app.workspace.activeLeaf.view.editor
    const cursorLine = editor.getCursor().line
    
	//Set the selection in the CodeMirror Editor
    editor.setSelection({line: cursorLine, ch: 0}, {line: cursorLine, ch: 9999})
	const id = createBlockHash();
	const block = `![[${tp.file.title}#^${id}]]`.split("\n").join("");

	// Copy the block reference to the clipboard
	navigator.clipboard.writeText(block).then(text => text);

	//Return the selected text and the generated block id
	return tp.file.selection() + `^${id}`.split("\n").join("");
}

//A simple function to create a random block id
function createBlockHash() {
	let result = '';
	var characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for ( var i = 0; i < 7; i++ ) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result;
}

//export the addBlockRef function
module.exports = addBlockRef

Ideas


up:: Plugin - Templater