Separating the URL from the item in Sitecore (Part 2)

Generating an appropriate Url for content based on user context

In Part 1 of this blog post, I showed how Sitecore can return content based on any arbitrary URL. Clearly that is only half of the story. A UK-based visitor should see “regional” links as:

http://website.com/uk/foo

The corollary to this requirement is that will also need a mechanism to generate a valid Url for items that don’t actually exist, so that where we used the Sitecore LinkManager previously, we could use a custom LinkManager and get a valid Url.

The second requirement can be fulfilled by extending the LinkManager class to support the appropriate Url types.

public class ProductLinkProvider : LinkProvider
{
 public override string GetItemUrl(Item item, UrlOptions options)
 {
 return item.IsRegionalItem() ? item.GetRegionalUrl() : base.GetItemUrl(item, options);
 }
}

 

public static class ItemExtensions
{
 public static string IsRegionalItem(this Item item)
 {
 // Code to identify "regional items"
 // Perhaps from a "Shared" area of the Content Tree
 }

 public static string GetRegionalUrl(this Item item)
 {
 // Code to generate appropriate Url
 }
}

In order for this code to be called, the Sublayout rendering the link needs to use the Sitecore rendering controls:

<sc:Link Field="Your Field Name" runat="server" />

or

<sc:FieldRenderer FieldName="Your Field Name" runat="server" />

This technique can be really powerful in separating your content items from their organisation, so that content editors and users can both have a site structure that they like.