How do I replace the contents of a file with Templater? Right now it only inserts the template at the cursor position

Things I have tried

I have tried:
<% tR += " NEW CONTENT" %>
which gives:
My OLD Content NEW CONTENTMy OLD Content

I have tried:
<% tR += " NEW CONTENT" %>
which gives:
NEW CONTENT NEW CONTENTMy OLD Content

I have tried:
<% tp.file.content %> NEW CONTENT
which gives:
My OLD Content NEW CONTENTMy OLD Content

I have tried:
<% tp.file.content.replace(tp.file.content, tp.file.content + " NEW CONTENT") %>
which gives:
My OLD Content NEW CONTENTMy OLD Content

I have tried:
<% tp.file.content = tp.file.content.replace(tp.file.content, tp.file.content + " NEW CONTENT") %>
which gives:
My OLD Content NEW CONTENTMy OLD Content

I have tried:
<%* tR += " New Content" %>
which gives:
New ContentMy OLD Content

What I’m trying to do

All I am trying to do is add some content to the end on the end of an existing file, but I can’t seem to modify the original content at all. It only adds the template to wherever the cursor is (at the start of the file in the example).

OK, I found a solution, but it isn’t very elegant. I am sure there must be a simpler way of appending something to a file.

For the time being, here is my workaround:

<%*
var file = app.workspace.getActiveFile()
var oldContent = await app.vault.read(file)
var newContent = " NEW CONTENT"
var joinedContent = oldContent += newContent
app.vault.modify(file, joinedContent)
%>
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.