Templater Plugin for Obsidian
Templater Plugin for Obsidian
Templateris a template language that lets you insert variables and functions results into your notes. It will also let you execute JavaScript code manipulating those variables and functions. WithTemplater, you will be able to create powerful templates to automate manual tasks.
背景描述:使用ob自带的template插入英文资源模板文件时需要手动替换template中的的 路径 及 文件名称,由于资源过多 且 需要替换的地方也有很多,手动替换费力
需求:设置 路径 和 文件名称 两个变量,插入模板时可以根据实际情况设置这两个变量的值
Terminology
- template: a file that contains commands.
- commands: a text snippet that starts with an opening tag <%, ends with a closing tag %>
- function: an object that we can invoke inside a command and that returns a value
Commands
<% tp.file.title %>
<%* tp.file.title %>- Interpolation command: output the result of the expression that's inside.
- JavaScript execution command: execute the JavaScript that's inside. It does not output anything by default.
expression: 在command中包含了variables 和 functions,它们组成expression。根据实际情况替换variables,计算expression得到最终结果
问:因为Interpolation command 内无法执行js,所以需要 Js execution command 来执行js?does not output: 上面两中类型的command的内容完全相同,但是insert 后只有一行(一个)文件标题,即js execution command的结果(expression)不会被输出(insert)
Js execution command can still access all the internal variables / functions
Js execution command let you access global namespace variables: app, moment
How to output a value from a Js Execution Command?
- command的结果被存储在一个名为
tR的variable中; tRis a replacement string- Js execution command 可以访问
tR - 问:Js execution command 的
tR默认是空?答:不是,Interpolation command 的结果会被添加到tR中,Js command默认不会,需要显示添加
=>如果要输入一个值就 append到 tR
示例:
<% tp.file.title %>
<%* tR += "输出js execution command中的内容" %>效果:
Test
输出js execution command中的内容tR计算的是截止到当前command的所有内容,包含command外- 可以重置
tR
<% tp.file.title %>
<%* tR = "" %>效果:
Example
<%* if (tp.file.title.startsWith("Hello")) { %>
This is a hello file !
<%* } else { %>
This is a normal file !
<%* } %>
<%*
function log(msg) {
console.log(msg);
}
%>
<%* log("Title: " + tp.file.title) %>console打印的内容可以在Develop Tools中查看(shift + ctrl + i)
有点没看懂
- 第一个command 只包含了if,对于后面的 This is a hello file! 有什么用?条件为真就会执行
- 为什么if的 }在第二个command内?
应用
英语资源模板
<%* let path = ""%>
<%* let name = ""%>
<%* tR=""; tR+=path + "/" + name; %>| 行号 | 功能 | 说明 |
|---|---|---|
| 1,2 | 定义路径,文件名称 变量 | |
| 3 | 拼接完整路径并存储 |
问题:
- 链接、音频中使用templater后格式显示不正确


答:虽然template中链接显示有问题,但是使用没有问题
如果实在看不下去,可以把链接字符放到command中。如:
<%* tR+="[mp3](resources/...)"; tR+=completePath; ... %>逐段拼接
- insert 后内容不正确
create a new note
tR不只包含了command 中expression的结果,command外的内容也在tR中。
将 tR设置为空,前面所有内容都将被清除。
将 tR清空的情景:template 文件本身有一些 frontmatter,和要insert的内容无关,无需这些frontmatter,那么在正文内容开始前可以把 tR 清空
- path及name的赋值
- path:根据提示框路径选择。获取并列举English下的所有文件夹名称,并在前面标上序号,根据序号选择路径。如果路径下仍包含文件夹,则继续列举。输入enter表示确认选择。esc表示返回上一级,如果在最上级,则esc表示退出?-》path设置为空
- name:将文件名称中的空格替换为-