5 Templates
A template is a layout an editor can choose for a page. If every page of a type looks the same, you need no template: code says what renders the type (chapter 8). If editors choose, say between a standard and a wide article layout, each choice is a template, and the page points at the one it uses:
the page the template the code
"Hello world", an IArticle "Article, wide"
Template ──────────────────► ViewName = "ArticleWide" ────► Views/Shared/ArticleWide.cshtml,
NodeTypes = [IArticle] rendered with the page as its modelTemplates are nodes, and editors create them like other content. Each template has:
| Field | What it is |
|---|---|
NodeTypes |
the page types it is for. A type includes the types derived from it, so IPage means every page. Empty means any type. |
| its kind | what renders it: the template's own node type, one of the four below |
| Kind | Renders with | Its fields |
|---|---|---|
IRazorViewTemplate |
a Razor view, with the page as its model | ViewName |
IMvcControllerTemplate |
an action of one of the site's controllers | Controller, and Action (Index when blank) |
IRazorPageTemplate |
a Razor Page | PagePath |
ITemplate, a plain template |
only a selector in Program.cs (chapter 8) |
In code, a template is created like any other node:
Guid typeOf<T>() => db.Datastore.Datamodel.NodeTypesByFullName[typeof(T).FullName!].Id;
var wide = db.CreateAndInsert<IRazorViewTemplate>(t => {
t.Name = "Article, wide";
t.ViewName = "ArticleWide";
t.NodeTypes = [typeOf<IArticle>()];
});
var article = db.CreateAndInsert<IArticle>(p => {
p.Name = "Hello world";
p.Template.Set(wide.Id);
});Two things to know:
- A view name in a template ties content to code. Rename
ArticleWide.cshtmland every template that names it breaks. A check at startup logs every name that no longer exists (chapter 8). NodeTypesholds type ids, so pin your types' ids. A type without a fixed id gets one from its full name, and its properties get theirs from the type's. If you rename or moveIArticle, the templates that list it point at nothing, and the stored articles no longer have a type. Give each type a fixed id with[Node(Id = "…")]from the start, and never change it. The CMS's own types have fixed ids.