blog
Using the Sitecore LinkManager for Creating Site-Aware Logic

One of the biggest challenges that I've faced on multi-site Sitecore solutions is creating site-aware features in contexts that are not site-aware, by default. Sitecore 8 has a lot of improvements for site-awareness, in components like Preview and the Experience Editors, but what about older versions, like Sitecore 7? Well, it turns out that the solution may be much easier than you think!

LinkManager to the rescue!

The Sitecore LinkManager includes a handy little method, ResolveTargetSite(Item item) that returns the SiteInfo object that a particular item in the tree belongs to.

You can use this method like so:

var item = ...
var site = Sitecore.Links.LinkManager.ResolveTargetSite(item);

The returned SiteInfo object can then be used in custom sc_site query string parameters or general site-aware logic. If you want to temporarily set the Sitecore.Context.Site to the returned SiteInfo, then you could do something like the following:

var item = ...
var site = Sitecore.Links.LinkManager.ResolveTargetSite(item);

using (new SiteContextSwitcher(site))
{
    // site-aware logic, here
}

Additional References

Didn't find what you were looking for? Mark Ursino has a great post on how you can manually resolve the context site based on the context item that might help get you started.

0 Comments
Post a Comment