Examples (template) - bhsd-harry/wikiparser-node GitHub Wiki

Other Languages

替换已弃用的模板参数

展开

假设有一个模板 Template:Foo,其中匿名参数 1 已弃用,推荐使用命名参数 bar,你可以在页面中将已弃用的参数替换为新参数。此示例演示了 TranscludeToken 的用法。

// Replacing deprecated template parameters (main)
// 包含 `Template:Foo` 的页面内容
import type {TranscludeToken} from "wikiparser-node";
const content = "{{Foo|Baz|Baz}}",
	root = Parser.parse(content),
	templates = root.querySelectorAll<TranscludeToken>("template#Template:Foo");
for (const template of templates) {
	if (template.hasArg(1)) {
		template.setValue("bar", template.getValue(1)!);
		template.removeArg(1);
	}
}
assert.equal(
	root,
	"{{Foo|2=Baz|bar=Baz}}",
);

替换已弃用的模板

展开

假设有一个模板 Template:Foo 已弃用,推荐使用参数相同的新模板 Template:Bar,你可以在页面中将已弃用的模板替换为新模板。此示例演示了 TranscludeToken 的用法。

// Replacing deprecated templates (main)
// 包含 `Template:Foo` 的页面内容
import type {TranscludeToken} from "wikiparser-node";
const content = "{{Foo|Bar|Baz}}",
	root = Parser.parse(content),
	templates = root.querySelectorAll<TranscludeToken>("template#Template:Foo");
for (const template of templates) {
	template.replaceTemplate("Bar");
}
assert.equal(
	root,
	"{{Bar|Bar|Baz}}",
);

替换模板为展开内容

展开

如果模板不太复杂,你可以在页面中将模板直接替换为其展开后的内容。此示例演示了 Token.prototype.expand 的用法。

// Substituting templates (main)
// `Template:Foo` 的内容
import type {TranscludeToken} from "wikiparser-node";
Parser.templates.set("Template:Foo", "{{Bar|{{{a|}}}|{{{b|}}}|true}}");
// `Template:Bar` 的内容
Parser.templates.set("Template:Bar", "{{#if:{{{3|}}}|{{{1|}}}\n{{{2|}}}\n}}");
// 包含 `Template:Foo` 的页面内容
const content = "{{Foo|a=Bar|b=Baz}}",
	root = Parser.parse(content),
	templates = root.querySelectorAll<TranscludeToken>("template#Template:Foo");
for (const template of templates) {
	template.replaceWith(template.expand());
}
assert.equal(
	root,
	`Bar
Baz`,
);
⚠️ **GitHub.com Fallback** ⚠️