Skip to content

Examples (template)

Bhsd edited this page Apr 15, 2026 · 6 revisions

Replacing deprecated template parameters

Expand

Given a template Template:Foo with an anonymouse parameter 1 which is deprecated in favor of a named parameter bar, you can replace the deprecated parameter with the new one in the content of a page. This example demonstrates the use of TranscludeToken.

// Replacing deprecated template parameters (main)
// The content of a page containing `Template:Foo`
var content = `{{Foo|Baz|Baz}}`,
	root = Parser.parse(content);
for (const template of root.querySelectorAll('template#Template:Foo')) {
	if (template.hasArg(1)) {
		template.setValue('bar', template.getValue(1));
		template.removeArg(1);
	}
}
assert.equal(
	root,
	'{{Foo|2=Baz|bar=Baz}}',
);

Replacing deprecated templates

Expand

Given a template Template:Foo which is deprecated in favor of Template:Bar with the same parameters, you can replace the deprecated template with the new one in the content of a page. This example demonstrates the use of TranscludeToken.

// Replacing deprecated templates (main)
// The content of a page containing `Template:Foo`
var content = `{{Foo|Bar|Baz}}`,
	root = Parser.parse(content);
for (const template of root.querySelectorAll('template#Template:Foo')) {
	template.replaceTemplate('Bar');
}
assert.equal(
	root,
	'{{Bar|Bar|Baz}}',
);

Substituting templates

Expand

You can substitute a template in the content of a page if the template is not too complex. This example demonstrates the use of Token.prototype.expand.

// Substituting templates (main)
// The content of `Template:Foo`
Parser.templates.set('Template:Foo', '{{Bar|{{{a|}}}|{{{b|}}}|true}}');
// The content of `Template:Bar`
Parser.templates.set('Template:Bar', '{{#if:{{{3|}}}|{{{1|}}}\n{{{2|}}}\n}}');
// The content of a page containing `Template:Foo`
var content = `{{Foo|a=Bar|b=Baz}}`,
	root = Parser.parse(content);
for (const template of root.querySelectorAll('template#Template:Foo')) {
	template.replaceWith(template.expand());
}
assert.equal(
	root,
	`Bar
Baz`,
);

Clone this wiki locally