Try our conversational search powered by Generative AI!

Loading...
Area: Optimizely CMS
ARCHIVED This content is retired and no longer maintained. See the latest version here.

Recommended reading 

Introduction

This document describes how to programmatically change the template that is used to render a page.

Example

Given that there is a typed page registered like:

C#
[ContentType]
public class TypedPage : PageData
{
    public virtual string Heading { get; set; }
    public virtual XhtmlString Content { get; set; }
}

It is possible to have several templates defined for the same typed page. The example below registers two templates for the same typed page. One is StandardTemplate that has property Default set to true in TemplateDescriptor attribute which states that this id the default template to use when rendering page instances of type TypedPage. The other template is another template that is more suitable for rendering for mobile devices.

C#
[TemplateDescriptor(Path = "~/templates/StandardPage.aspx", Default = true)]
public partial class StandardTemplate : TemplatePage<TypedPage>
{ }

[TemplateDescriptor(Path = "~/templates/MobilePage.aspx", Name = "MobileTemplate")]
public partial class MobileTemplate : TemplatePage<TypedPage>
{ }

To change the template that is used for a request you can attach an event handler to an event that is raised when a template is to be chosen for a specific request. The code sample below attaches to the event and changes the template for request for TypedPage instances when the request comes from a mobile device.

C#
[InitializableModule]
public class MobileRedirectSample : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
        context.Locate.TemplateResolver().TemplateResolved 
            += new EventHandler<TemplateResolverEventArgs>(MobileRedirectSample_TemplateResolved);
    }

    public void Uninitialize(global::EPiServer.Framework.Initialization.InitializationEngine context)
    {
        context.Locate.TemplateResolver().TemplateResolved
            -= new EventHandler<TemplateResolverEventArgs>(MobileRedirectSample_TemplateResolved);
    }

    void MobileRedirectSample_TemplateResolved(object sender, TemplateResolverEventArgs eventArgs)
    {
        if (eventArgs.ItemToRender != null && eventArgs.ItemToRender is TypedPage &&
            HttpContext.Current.Request.Browser.IsMobileDevice)
        {
            var mobileRender = eventArgs.SupportedTemplates
                .SingleOrDefault(r => r.Name.Contains("Mobile") &&
                r.TemplateTypeCategory == eventArgs.SelectedTemplate.TemplateTypeCategory);

            if (mobileRender != null)
            {
                eventArgs.SelectedTemplate = mobileRender;
            }
        }
    }

    public void Preload(string[] parameters)
    {
    }
}
Do you find this information helpful? Please log in to provide feedback.

Last updated: Mar 25, 2013

Recommended reading