obsidian-templater
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTemplater 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
核心模板语法
| Tag | Behavior |
|---|---|
| Outputs the result of the expression |
| Executes JS code; no output by default |
| 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 string:
<%* %>tR<%* tR += "some output" %>To discard everything generated up to a point (e.g., strip template-only frontmatter):
<%* tR = "" -%>All functions are available in both tag types.
tp.*| 标签 | 行为 |
|---|---|
| 输出表达式的结果 |
| 执行JS代码;默认无输出 |
| 在预览模式下重新计算(已弃用,避免使用) |
| 修剪标签前后的一个换行符 |
| 修剪标签前后的所有空白字符 |
要从执行块中输出内容,需追加到特殊的字符串:
<%* %>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. uses moment.js tokens ( is the default). is a number of days (, ) or a duration string (). is a date string parsed with .
format"YYYY-MM-DD"offset7-1"P1W"referencereference_formattp.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 globallyCommon 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?)返回格式化后的日期字符串。使用moment.js标记(默认值为)。为天数(、)或时长字符串()。是使用解析的日期字符串。
format"YYYY-MM-DD"offset7-1"P1W"referencereference_formattp.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 fileFunctions:
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 inside blocks:
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?)suggesterjavascript
<%* const type = await tp.system.suggester(["Meeting", "Decision", "Reference"], ["meeting", "decision", "ref"]) %>所有方法均为异步方法——需在块中使用:
<%* %>awaitawait 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?)suggesterjavascript
<%* 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 if the property doesn't exist.
undefined直接访问属性——无需调用函数:
<% tp.frontmatter.status %>
<% tp.frontmatter.project %>若属性不存在则返回。
undefinedtp.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.appApptp.obsidiantp.appApptp.obsidiantp.hooks
tp.hooks
tp.hooks.on_all_templates_executed(callback)Callback fires after all nested templates (e.g., from ) have finished.
tp.file.create_newtp.hooks.on_all_templates_executed(callback)所有嵌套模板(例如通过创建的模板)执行完成后,回调函数将触发。
tp.file.create_newUser-defined functions (tp.user)
用户自定义函数(tp.user)
Scripts placed in the folder configured in Templater settings are callable as . Scripts use CommonJS format:
tp.user.<filename>(args...)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 as an argument to access Templater context inside a script. Note: user functions are unavailable on mobile.
tp放置在Templater设置中配置的文件夹内的脚本可通过调用。脚本采用CommonJS格式:
tp.user.<文件名>(参数...)javascript
// Scripts/slugify.js
module.exports = function (text) {
return text.toLowerCase().replace(/\s+/g, "-");
};<% tp.user.slugify(tp.file.title) %>脚本也可导出一个包含命名函数的对象。将作为参数传入,可在脚本内部访问Templater上下文。注意:用户自定义函数在移动端不可用。
tpWhitespace control in templates
模板中的空白字符控制
Control flow tags (, ) leave blank lines by default. Use to trim the newline that follows a tag:
<%* if (...) { %><%* } %>-%><%* 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() %>
undefinedPrompted 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() %>
undefinedStrip 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() %>
undefinedundefinedConditional content by folder
按文件夹显示条件内容
<%* if (tp.file.folder() === "Work") { -%>
**Project:** <% tp.frontmatter.project ?? "unassigned" %>
<%* } else { -%>
**Topic:**
<%* } -%>For subfolder matching: — returns the full vault-relative path.
tp.file.folder(true).startsWith("Work/")folder(true)<%* 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 strings for or when manipulating dates inside blocks using the global.
formattp.date.now()<%* %>moment如需全面的格式速查表和JS操作参考,请查看momentjs.md。在为定义字符串时,或在块中使用全局对象操作日期时,可参考此文档。
tp.date.now()format<%* %>momentOptional 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 referenceAsk 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