GeneralLink in Sitecore

前端 未结 6 844
囚心锁ツ
囚心锁ツ 2020-12-03 12:26

I\'m new to Sitecore.. I have created a Page template and add a field for a URL of type General Link. I have created another field for the text for the link (this is standar

6条回答
  •  -上瘾入骨i
    2020-12-03 12:33

    You should be careful using linkField.Url since it it will incorrectly render internal links to Sitecore Items and Media. You should instead be using Sitecore.Links.LinkManager.GetItemUrl(item) and Sitecore.Resources.Media.MediaManager.GetMediaUrl(item) for those.

    It would be better to have a helper (extension) method to return the correct url for you, based on the type of link. Take a look this Sitecore Links with LinkManager and MediaManager blog post which has the correct code you need for this.

    For reference:

    public static String LinkUrl(this Sitecore.Data.Fields.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;
        }
    }
    

    Usage:

    Sitecore.Data.Fields.LinkField linkField = item.Fields["Link1"];
    lnkMain.NavigateUrl = linkField.LinkUrl();
    

    It would be best of course to use control and let Sitecore handle it for you, but it looks like you do not have that option.

提交回复
热议问题