renderTemplate

Loads a template from the template directory, applies the given context variables, and returns the html document in dom format. You can use Document.toString to make a string.

renderTemplate
(,
var context = var.emptyObject
,
var skeletonContext = var.emptyObject
,
string skeletonName = null
,)

Parameters

templateName string

the name of the main template to load. This is usually a .html filename in the templates directory (but see also the loader param)

context var

the global object available to scripts inside the template

skeletonContext var

the global object available to the skeleton template

skeletonName string

the name of the skeleton template to load. This is usually a .html filename in the templates directory (but see also the loader param), and the skeleton file has the boilerplate html and defines placeholders for the main template

loader TemplateLoader

a class that defines how to load templates by name. If you pass null, it uses a default implementation that loads files from the templates/ directory.

Examples

Shows how top-level things from the template are moved to their corresponding items on the skeleton.

// for the unittest, we want to inject a loader that uses plain strings instead of files.
auto testLoader = new class TemplateLoader {
	string loadTemplateHtml(string name) {
		switch(name) {
			case "skeleton":
				return `
					<html>
						<head>
							<!-- you can define replaceable things with ids -->
							<!-- including <document-fragment>s which are stripped out when the template is finalized -->
							<document-fragment id="header-stuff" />
						</head>
						<body>
							<main></main>
						</body>
					</html>
				`;
			case "main":
				return `
					<main>Hello</main>
					<document-fragment id="header-stuff">
						<title>My title</title>
					</document-fragment>
				`;
			default: assert(0);
		}
	}
};

Document doc = renderTemplate("main", var.emptyObject, var.emptyObject, "skeleton", testLoader);

assert(doc.querySelector("document-fragment") is null); // the <document-fragment> items are stripped out
assert(doc.querySelector("title") !is null); // but the stuff from inside it is brought in
assert(doc.requireSelector("main").textContent == "Hello"); // and the main from the template is moved to the skeelton

Meta

History

Parameter loader was added on December 11, 2023 (dub v11.3)