Skip to content

Instantly share code, notes, and snippets.

@ninjaonsafari
Created January 30, 2015 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninjaonsafari/21c20c18572bd24e0ad5 to your computer and use it in GitHub Desktop.
Save ninjaonsafari/21c20c18572bd24e0ad5 to your computer and use it in GitHub Desktop.
This code snippet changes the template on the request if its a mobile
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