Buttons with Templater code in Templater template

Since I was not able to find a proper solution online, I thought it would be nice to post my solution here. The case.

I wanted a button, using the buttons plugin, that triggered templater code, while the button is part of a Templater template. The challenge in this case is that once you put the button that holds the templater code in a template, the code is executed along with the template execution itself, leaving you with an “empty button” and the code (in my case a move action) executed.

So the regular button code is:

```button
name Close
type note(<% tp.file.move("Dossiers/Closed/" + tp.file.title) %>) template
action test
templater true
```

Once you want to put it into a templater template, you have to find a way to escape the <% and %> in a way that they are presented in the correct format once the note is created. I figured out this was possible using String.fromCharCode(). So to get the button shown above into a note that is created by a Templater template, one should add the following code in the template:

```button
name Close
type note(<% String.fromCharCode(60, 37) %> tp.file.move("Dossiers/Closed/" + tp.file.title) <% String.fromCharCode(37, 62) %>) template
action test
templater true
```

60 is the ASCII value of <, 37 of & and 62 of >. It’s not unlikely that there are other ways to achieve the same goal, and perhaps even better ways, but this is the solution I found. Feel free to enrich this topic with other solutions that might help others in achieving their goal.

2 Likes

A shorter way is to just type the opening tag as a literal string, and the closing tag as an escaped literal string (I have no idea why the opening tag can be typed as is but the closing tag must be escaped - must be something in the parsing engine :man_shrugging: )

```button
name Close
type note(<% '<%' %> ... ... ... <% '\%\>' %>) template
action test
templater true

For consistency you can obviously escape the opening tag as well.

[edit: HAH! apparently you can get away with just escaping the ‘>’ character in the closing tag - minimum number of typed characters, like this:

type note(<% '<%' %> ... ... ... <% '%\>' %>) template
1 Like