Since Page Templates are part of the MVC application (and not the CMS) APIs to interact with things like Page Templates are not available in Xperience's shared libraries since these are used in both the CMS and live site applications.
Additionally, programmatically setting a Page Template isn't considered a standard use case for Xperience, so there actually aren't any publicly accessible APIs to set a Page Template on a TreeNode
.
That said, Xperience doesn't prevent you from setting one!
if (parentPage != null)
{
// Creates a new page of the custom page type
TreeNode newPage = TreeNode.New("PageType.PageMenuItem");
// Sets the properties of the new page
newPage.DocumentName = "TestPage";
newPage.DocumentCulture = "en-us";
var pageTemplateConfig = new
{
identifier = "Your.PageTemplateIdentifier",
properties = null // You can specify properties here if your Page Template has them
};
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
newPage.SetValue(
"DocumentPageTemplateConfiguration",
JsonConvert.SerializeObject(pageTemplateConfig, serializerSettings));
// Inserts the new page as a child of the parent page
newPage.Insert(parentPage);
}
How you populate the Page Template configuration really depends on where this code is executing. If it's in a library shared between the CMS and live site (the most likely situation), it's up to you to maintain the properties
of the Page Template configuration manually, making sure it has the correct property names and values to match the IPageTemplateProperties
of the Page Template assigned to the identifier
.
I typically set properties
to null
when I can because it simplifies the code maintenance over time. But sometimes you need to pre-populate a new page with a specific configuration, in which case you need to keep it aligned with the shape of the IPageTemplateProperties
for the Page Template.