Thursday, October 30, 2014

Sitecore get URL for LinkField

A Sitecore template field of General Link type, can link to various items of various types (internal, external, media items and so on). Because each type would be rendered differently, when accessing these links in code, the different types need to be taken into account. The following method (found online) would take in a LinkField and output the URL as a string.

A LinkField comes from accesing a Sitecore item's template field liek follows: LinkField link = item.Fields["Field Name"]; This object can then be passed into the following method to get the correct URL:
/// <summary>
/// Get the URL for a given sitecore linkfield
/// </summary>
/// <param name="lf">sitecore linkfield</param>
/// <returns>web URL</returns>
public static string GetLinkFieldURL(LinkField lf)
{
    switch (lf.LinkType.ToLower())
    {
        case "internal":
            // Use LinkMananger for internal links, if link is not empty
            return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty;
        case "media":
            // Use MediaManager for media links, if link is not empty
            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