Parse Sitecore General Link field

While I am aware that rendering parameters ideally should not contain content, our component has the special need which created the need to add a general link field on the rendering parameters template of a rendering.

Question came though – when we needed to use the data from this parameter. As we know, rendering parameters are only available in the code as strings, while general link field information is stored in an xml.

We needed these links to only support internal links, so the code does just that, however, you can obviously build on this, or use Sitecore’s internal properties on link field renderer to extend this code.

Here’s how we did it:

  [XmlRoot("link")]
  [Serializable]
  public class BasicLink
  {
    [XmlAttribute]
    public string text { get; set; }

    [XmlAttribute]
    public string anchor { get; set; }

    [XmlAttribute]
    public string linktype { get; set; }

    [XmlAttribute]
    public string @class { get; set; }

    [XmlAttribute]
    public string title { get; set; }

    [XmlAttribute]
    public string target { get; set; }

    [XmlAttribute]
    public string querystring { get; set; }

    [XmlAttribute]
    public string id { get; set; }

    public string Url
    {
      get
      {
        if (this.linktype == LinkType.Internal.ToString() && !this.id.IsNullOrWhiteSpace() && this.id.IsGuid())
          return LinkManager.GetItemUrl(Sitecore.Context.Database.GetItem(new ID(this.id)));
        return string.Empty;
      }
    }
  }

We then added a HTML helper extension method to allow us to transform the raw general link field data into the above new class:

public static BasicLink ToLink(this string raw)
    {
      if (string.IsNullOrWhiteSpace(raw))
        return (BasicLink) null;
      return (BasicLink) new XmlSerializer(typeof (BasicLink), new XmlRootAttribute("link")).Deserialize((TextReader) new StringReader(raw));
    }

Here’s a sample of the usage:

BasicLink ViewMoreLink = RenderingContext.Current.Rendering.Parameters["View More Link].ToLink(),

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s