Created
January 30, 2015 14:30
-
-
Save wiedikerli/21c20c18572bd24e0ad5 to your computer and use it in GitHub Desktop.
This code snippet changes the template on the request if its a mobile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using umbraco; | |
using umbraco.BusinessLogic; | |
using Umbraco.Core; | |
using Umbraco.Core.Models; | |
using Umbraco.Core.Services; | |
using Umbraco.Web.Routing; | |
namespace PROJECTNAME.Web.Mvc.Mobile | |
{ | |
public class MobileHandler : IApplicationEventHandler | |
{ | |
public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ } | |
public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
PublishedContentRequest.Prepared += (sender, args) => | |
{ | |
if (IsMobile(sender as PublishedContentRequest)) | |
{ | |
// Check to make sure the request is valid | |
var request = sender as PublishedContentRequest; | |
if (request == null || !request.HasPublishedContent || !request.HasTemplate) | |
return; | |
var node = request.PublishedContent; | |
// Gets current Template from request | |
var template = applicationContext.Services.FileService.GetTemplate(node.TemplateId) as Template; | |
// Get mobile template | |
var mobileTemplate = applicationContext.Services.FileService.GetTemplate(template.Alias + "_Mobile"); | |
// change requested template to the mobile one | |
request.SetTemplate(mobileTemplate as ITemplate); | |
} | |
}; | |
} | |
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ } | |
private bool IsMobile(PublishedContentRequest sender) | |
{ | |
if (sender == null) | |
{ | |
return false; | |
} | |
return sender.Uri.AbsoluteUri.IndexOf("://m.") >= 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment