Tuesday, May 10, 2016

Getting Sitecore links with the server URL

I was working on a sublayout that needed to use an internal RSS feed as a datasource. The code which parsed the RSS feed for items however did not like using relative URLs. The solution here was to query Sitecore for the link with options to include the server URL.

var urlOptions = new UrlOptions { AlwaysIncludeServerUrl = true };
Sitecore.Links.LinkManager.GetItemUrl(MyItem, urlOptions)

This can also be done for media items:

var urlOptions = new MediaUrlOptions { AlwaysIncludeServerUrl = true };
Sitecore.Resources.Media.MediaManager.GetMediaUrl(MyMediaItem, urlOptions)

Most of us are familiar with the classic function available on Stack Overflow which takes in a Sitecore linkfield and returns the correct URL for each possible type of link (internal, media, external and so on). This can also be modified to output the URLs with server URL if required:

public static string GetLinkFieldUrl(LinkField lf, bool includeServerUrl = false)
{
    switch (lf.LinkType.ToLower())
    {
        case "internal":
            // Use LinkMananger for internal links, if link is not empty
            if (includeServerUrl)
            {
                var urlOptions = new UrlOptions { AlwaysIncludeServerUrl = true };
                return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem, urlOptions) : string.Empty;
            }
            else
            {
                return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty;
            } 
        case "media":
            // Use MediaManager for media links, if link is not empty
            if (includeServerUrl)
            {
                var urlOptions = new MediaUrlOptions { AlwaysIncludeServerUrl = true };
                return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem, urlOptions) : string.Empty;
            }
            else
            {
                return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty;
            }
                    
        case "external":
            // Just return external links
            return lf.Url;
        case "anchor":
            // Prefix anchor link with # if link if not empty
            return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty;
        case "mailto":
            // Just return mailto link
            return lf.Url;
        case "javascript":
            // Just return javascript
            return lf.Url;
        default:
            // Just please the compiler, this
            // condition will never be met
            return lf.Url;
    }
}

No comments:

Post a Comment