obsidian-templater

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Templater template generation

Templater模板生成

Templater is an Obsidian plugin for dynamic note templates. Commands embedded in a template file run when the template is applied to a note, outputting results inline.
Templater是Obsidian的一款动态笔记模板插件。嵌入在模板文件中的命令会在模板应用到笔记时运行,并将结果内联输出。

Core template syntax

核心模板语法

TagBehavior
<% expression %>
Outputs the result of the expression
<%* code %>
Executes JS code; no output by default
<%+ expression %>
Re-evaluated in preview mode (deprecated, avoid)
<%-
/
-%>
Trims one newline before/after the tag
<%_
/
_%>
Trims all whitespace before/after the tag
To output from a
<%* %>
execution block, append to the special
tR
string:
<%* tR += "some output" %>
To discard everything generated up to a point (e.g., strip template-only frontmatter):
<%* tR = "" -%>
All
tp.*
functions are available in both tag types.

标签行为
<% expression %>
输出表达式的结果
<%* code %>
执行JS代码;默认无输出
<%+ expression %>
在预览模式下重新计算(已弃用,避免使用)
<%-
/
-%>
修剪标签前后的一个换行符
<%_
/
_%>
修剪标签前后的所有空白字符
要从
<%* %>
执行块中输出内容,需追加到特殊的
tR
字符串:
<%* tR += "some output" %>
要丢弃截至当前点生成的所有内容(例如,移除仅模板专用的前置元数据):
<%* tR = "" -%>
所有
tp.*
函数在两种标签类型中均可使用。

Built-in Templater modules

Templater内置模块

tp.date

tp.date

tp.date.now(format?, offset?, reference?, reference_format?)
Returns a formatted date string.
format
uses moment.js tokens (
"YYYY-MM-DD"
is the default).
offset
is a number of days (
7
,
-1
) or a duration string (
"P1W"
).
reference
is a date string parsed with
reference_format
.
tp.date.tomorrow(format?)        // today + 1 day
tp.date.yesterday(format?)       // today - 1 day
tp.date.weekday(format, weekday, reference?, reference_format?)
                                 // weekday: 0=Sun … 6=Sat
moment                           // full moment.js object, accessible globally
Common format strings:
"YYYY-MM-DD"
,
"YYYY-MM-DD HH:mm"
,
"dddd Do MMMM YYYY"
,
"HH:mm"
,
"ddd"
,
"MMM D"
.

tp.date.now(format?, offset?, reference?, reference_format?)
返回格式化后的日期字符串。
format
使用moment.js标记(默认值为
"YYYY-MM-DD"
)。
offset
为天数(
7
-1
)或时长字符串(
"P1W"
)。
reference
是使用
reference_format
解析的日期字符串。
tp.date.tomorrow(format?)        // 今日+1天
tp.date.yesterday(format?)       // 今日-1天
tp.date.weekday(format, weekday, reference?, reference_format?)
                                 // weekday: 0=周日 … 6=周六
moment                           // 全局可访问的完整moment.js对象
常用格式字符串:
"YYYY-MM-DD"
"YYYY-MM-DD HH:mm"
"dddd Do MMMM YYYY"
"HH:mm"
"ddd"
"MMM D"

tp.file

tp.file

Dynamic properties (not function calls — no parentheses):
tp.file.title      // basename without extension
tp.file.content    // full text of the file
tp.file.tags       // string[] of all tags on the file
Functions:
tp.file.creation_date(format?)                 // default "YYYY-MM-DD HH:mm"
tp.file.last_modified_date(format?)            // default "YYYY-MM-DD HH:mm"
tp.file.folder(absolute?)                      // folder name; full path if absolute=true
tp.file.path(relative?)                        // absolute path; vault-relative if relative=true
tp.file.cursor(order?)                         // place cursor here after template runs; order = tab index
tp.file.cursor_append(content)                 // insert content at the current cursor
tp.file.selection()                            // currently selected text in the editor
tp.file.exists(filepath)                       // async → boolean
tp.file.find_tfile(filename)                   // → TFile | null (for use with create_new / include)
tp.file.include("[[NoteLink]]")                // async; embeds another note's content (also processed)
tp.file.create_new(template, filename, open_new?, folder?)  // async; create note from template
tp.file.move(path, file?)                      // async; move file (path has no extension)
tp.file.rename(new_title)                      // async; rename the current file

动态属性(无需调用函数——不需要括号):
tp.file.title      // 不含扩展名的基础文件名
tp.file.content    // 文件的完整文本
tp.file.tags       // 文件中所有标签的字符串数组
函数:
tp.file.creation_date(format?)                 // 默认值为"YYYY-MM-DD HH:mm"
tp.file.last_modified_date(format?)            // 默认值为"YYYY-MM-DD HH:mm"
tp.file.folder(absolute?)                      // 文件夹名称;若absolute=true则返回完整路径
tp.file.path(relative?)                        // 绝对路径;若relative=true则返回相对于库的路径
tp.file.cursor(order?)                         // 模板运行后将光标置于此处;order为Tab索引
tp.file.cursor_append(content)                 // 在当前光标位置插入内容
tp.file.selection()                            // 编辑器中当前选中的文本
tp.file.exists(filepath)                       // 异步方法 → 布尔值
tp.file.find_tfile(filename)                   // → TFile | null(用于create_new / include)
tp.file.include("[[NoteLink]]")                // 异步方法;嵌入另一个笔记的内容(同样会被处理)
tp.file.create_new(template, filename, open_new?, folder?)  // 异步方法;根据模板创建笔记
tp.file.move(path, file?)                      // 异步方法;移动文件(path不含扩展名)
tp.file.rename(new_title)                      // 异步方法;重命名当前文件

tp.system

tp.system

All are async — use
await
inside
<%* %>
blocks:
await tp.system.clipboard()
await tp.system.prompt(prompt_text, default_value?, throw_on_cancel?, multi_line?)
await tp.system.suggester(text_items, items, throw_on_cancel?, placeholder?, limit?)
await tp.system.multi_suggester(text_items, items, throw_on_cancel?, title?, limit?)
suggester
takes two parallel arrays: display labels and return values. They can be the same array.
javascript
<%* const type = await tp.system.suggester(["Meeting", "Decision", "Reference"], ["meeting", "decision", "ref"]) %>

所有方法均为异步方法——需在
<%* %>
块中使用
await
await tp.system.clipboard()
await tp.system.prompt(prompt_text, default_value?, throw_on_cancel?, multi_line?)
await tp.system.suggester(text_items, items, throw_on_cancel?, placeholder?, limit?)
await tp.system.multi_suggester(text_items, items, throw_on_cancel?, title?, limit?)
suggester
接收两个并行数组:显示标签和返回值。两者可以是同一个数组。
javascript
<%* const type = await tp.system.suggester(["Meeting", "Decision", "Reference"], ["meeting", "decision", "ref"]) %>

tp.frontmatter

tp.frontmatter

Direct property access — not a function:
<% tp.frontmatter.status %>
<% tp.frontmatter.project %>
Returns
undefined
if the property doesn't exist.

直接访问属性——无需调用函数:
<% tp.frontmatter.status %>
<% tp.frontmatter.project %>
若属性不存在则返回
undefined

tp.web

tp.web

All are async:
await tp.web.daily_quote()                        // Obsidian callout block with a random quote
await tp.web.random_picture(size, query?, include_size?)
    // size: "800" or "800x600"; returns markdown image syntax
await tp.web.request(url, path?)
    // HTTP GET returning JSON; path is dot-notation like "data.title"

所有方法均为异步方法:
await tp.web.daily_quote()                        // 带随机名言的Obsidian提示块
await tp.web.random_picture(size, query?, include_size?)
    // size: "800"或"800x600";返回Markdown图片语法
await tp.web.request(url, path?)
    // HTTP GET请求,返回JSON;path为点标记法,例如"data.title"

tp.config

tp.config

Read-only context about the current run:
tp.config.template_file    // TFile of the template being applied
tp.config.target_file      // TFile of the note being created/modified
tp.config.active_file      // TFile of the currently active file
tp.config.run_mode         // 0=CreateNewFromTemplate 1=AppendActiveFile 2=OverwriteFile
                           // 3=OverwriteActiveFile 4=DynamicProcessor

关于当前运行的只读上下文:
tp.config.template_file    // 当前应用的模板文件对应的TFile
tp.config.target_file      // 正在创建/修改的笔记对应的TFile
tp.config.active_file      // 当前激活文件对应的TFile
tp.config.run_mode         // 0=从模板新建 1=追加到激活文件 2=覆盖文件
                           // 3=覆盖激活文件 4=动态处理器

App and Obsidian API modules

应用与Obsidian API模块

tp.app
is the Obsidian
App
object.
tp.obsidian
exposes the Obsidian API module. Used in advanced JS execution blocks for vault traversal, metadata cache queries, etc.

tp.app
是Obsidian的
App
对象。
tp.obsidian
暴露Obsidian API模块。用于高级JS执行块中,实现库遍历、元数据缓存查询等操作。

tp.hooks

tp.hooks

tp.hooks.on_all_templates_executed(callback)
Callback fires after all nested templates (e.g., from
tp.file.create_new
) have finished.

tp.hooks.on_all_templates_executed(callback)
所有嵌套模板(例如通过
tp.file.create_new
创建的模板)执行完成后,回调函数将触发。

User-defined functions (tp.user)

用户自定义函数(tp.user)

Scripts placed in the folder configured in Templater settings are callable as
tp.user.<filename>(args...)
. Scripts use CommonJS format:
javascript
// Scripts/slugify.js
module.exports = function (text) {
  return text.toLowerCase().replace(/\s+/g, "-");
};
<% tp.user.slugify(tp.file.title) %>
Scripts can also export an object of named functions. Pass
tp
as an argument to access Templater context inside a script. Note: user functions are unavailable on mobile.

放置在Templater设置中配置的文件夹内的脚本可通过
tp.user.<文件名>(参数...)
调用。脚本采用CommonJS格式:
javascript
// Scripts/slugify.js
module.exports = function (text) {
  return text.toLowerCase().replace(/\s+/g, "-");
};
<% tp.user.slugify(tp.file.title) %>
脚本也可导出一个包含命名函数的对象。将
tp
作为参数传入,可在脚本内部访问Templater上下文。注意:用户自定义函数在移动端不可用。

Whitespace control in templates

模板中的空白字符控制

Control flow tags (
<%* if (...) { %>
,
<%* } %>
) leave blank lines by default. Use
-%>
to trim the newline that follows a tag:
<%* if (tp.file.folder() === "Work") { -%>
**Project:** <% tp.frontmatter.project %>
<%* } else { -%>
General note
<%* } -%>

控制流标签(
<%* if (...) { %>
<%* } %>
)默认会留下空行。使用
-%>
修剪标签后的换行符:
<%* if (tp.file.folder() === "Work") { -%>
**项目:** <% tp.frontmatter.project %>
<%* } else { -%>
通用笔记
<%* } -%>

Common implementation patterns

常见实现模式

Daily note

每日笔记

---
date: <% tp.date.now() %>
---

<< [[<% tp.date.yesterday() %>]] | [[<% tp.date.tomorrow() %>]] >>
---
date: <% tp.date.now() %>
---

<< [[<% tp.date.yesterday() %>]] | [[<% tp.date.tomorrow() %>]] >>

<% tp.file.title %>

<% tp.file.title %>

<%* tR += await tp.web.daily_quote() %>
<% tp.file.cursor() %>
undefined
<%* tR += await tp.web.daily_quote() %>
<% tp.file.cursor() %>
undefined

Prompted metadata + file rename

带提示的元数据 + 文件重命名

<%*
const title = await tp.system.prompt("Note title", tp.file.title)
const status = await tp.system.suggester(["Draft", "In progress", "Done"], ["draft", "in-progress", "done"])
await tp.file.rename(title)
-%>
---
title: <% title %>
status: <% status %>
created: <% tp.file.creation_date() %>
---
<%*
const title = await tp.system.prompt("笔记标题", tp.file.title)
const status = await tp.system.suggester(["Draft", "In progress", "Done"], ["draft", "in-progress", "done"])
await tp.file.rename(title)
-%>
---
title: <% title %>
status: <% status %>
created: <% tp.file.creation_date() %>
---

<% title %>

<% title %>

<% tp.file.cursor() %>
undefined
<% tp.file.cursor() %>
undefined

Strip template-file frontmatter from output

从输出中移除模板文件的前置元数据

---
type: template
description: This is a person template.
---

<%* tR = "" -%>
---
type: person
created: <% tp.file.creation_date() %>
---
---
type: template
description: This is a person template.
---

<%* tR = "" -%>
---
type: person
created: <% tp.file.creation_date() %>
---

<% tp.file.cursor() %>

<% tp.file.cursor() %>

undefined
undefined

Conditional content by folder

按文件夹显示条件内容

<%* if (tp.file.folder() === "Work") { -%>
**Project:** <% tp.frontmatter.project ?? "unassigned" %>
<%* } else { -%>
**Topic:**
<%* } -%>
For subfolder matching:
tp.file.folder(true).startsWith("Work/")
folder(true)
returns the full vault-relative path.
<%* if (tp.file.folder() === "Work") { -%>
**项目:** <% tp.frontmatter.project ?? "未分配" %>
<%* } else { -%>
**主题:**
<%* } -%>
匹配子文件夹:
tp.file.folder(true).startsWith("Work/")
——
folder(true)
返回完整的相对于库的路径。

Include another note

嵌入另一个笔记

<% await tp.file.include("[[Shared Header]]") %>

<% await tp.file.include("[[Shared Header]]") %>

Date formatting with Moment.js

使用Moment.js格式化日期

See momentjs.md for a comprehensive formatting cheatsheet and JS manipulation reference. Use this when defining
format
strings for
tp.date.now()
or when manipulating dates inside
<%* %>
blocks using the
moment
global.

如需全面的格式速查表和JS操作参考,请查看momentjs.md。在为
tp.date.now()
定义
format
字符串时,或在
<%* %>
块中使用全局
moment
对象操作日期时,可参考此文档。

Optional vault integration via obsidian-cli

通过obsidian-cli实现可选的库集成

If the obsidian-cli skill is available and Obsidian is running, vault context can improve output:
bash
obsidian properties counts          # what frontmatter properties exist across the vault
obsidian tags counts sort=count     # most-used tags
obsidian read file="Daily Note"     # read an existing template for style reference
Ask the user before running any CLI commands.

如果obsidian-cli可用且Obsidian正在运行,库上下文可优化输出:
bash
obsidian properties counts          # 查看库中存在哪些前置元数据属性
obsidian tags counts sort=count     # 查看使用频率最高的标签
obsidian read file="Daily Note"     # 读取现有模板以参考样式
在运行任何CLI命令前,请先询问用户。

Official documentation links

官方文档链接

Rendered docs (human-readable): https://silentvoid13.github.io/Templater/
LLM-safe Templater summary: For a preprocessed, audit-friendly summary of the official Templater documentation, see
https://context7.com/silentvoid13/templater/llms.txt
.
渲染版文档(易读性强): https://silentvoid13.github.io/Templater/
适合LLM的Templater摘要: 如需经过预处理、审计友好的官方Templater文档摘要,请查看
https://context7.com/silentvoid13/templater/llms.txt