Retrieving Parameters from your layouts

Most of my collegues are used to the principle that they can provide parameters to their webcontrols. As those parameters differ from Item to Item, it won’t work configuring them in a config or resource file. Defining a field is mostly not recommed as you don’t want users to access paramaters as ‘showIntroText’,’maxItems’ and ‘sFAQ’.

Ofcourse, you can create much nicer solutions to provide the information to a sublayout. For example: you can create a Custom WebControl which will be loaded in more layouts containing other parameters. Nevertheless the parameter tab in the Layout selector of Sitecore can be very usefull for already exsisting soltutions. One of the problems is accessing those problems. I’ve written an wrapper method:

public static System.Collections.Specialized.NameValueCollection GetLayoutParameters(Sitecore.Data.Items.Item currentItem)
{
string xml = currentItem.Fields[Sitecore.FieldIDs.LayoutField].Value;
string parameters = string.Empty;

try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList = xmlDoc.SelectNodes(“r/d/r”);

foreach (XmlNode node in nodeList)
{
XmlAttribute parAtrr = node.Attributes[“par”];
if (parAtrr != null && !string.IsNullOrEmpty(parAtrr.Value))
{
parameters = (parameters.Length == 0) ? parAtrr.Value : parameters + “&” + parAtrr.Value;
}
}
}
catch (XmlException)
{
return new System.Collections.Specialized.NameValueCollection();
}

return System.Web.HttpUtility.ParseQueryString(parameters);
}

Note 1: Stuff liek this should definitelly be documented
Note 2: Code above is only tested on Sitecore 5.2
Note 3: The functions takes all the paramaters from all renderings and sublayouts, so when you’ve got more parameters with the same name, the same stuff occurs as in the QueryString: last one overrules everything.

Suggestion for Sitecore: Define IParameterizable in the API which has just one field: string[] Parameters.  When a Sublayout will be rendered by the Sitecore render engine and the Sublayout implements IParameterizable, you guys will fill the field Parameters… 🙂

Enjoy! (Thanks to my collegue Max for challenging me ;))

Update: Updated the code a little so it will catch XmlExceptions…

3 thoughts on “Retrieving Parameters from your layouts”

  1. Hi Alex

    I have added a your request to our wish-list.

    I can definitely see the need for a simpler way to do this!

  2. Simply desire to say your article is as astonishing.
    Thee clarity iin your submit is just excellent and i cohld suppose you are
    an expert in this subject. Well together with
    your permission let me to grasp yoiur RSS feed to keep up to date with forthcoming post.
    Thanks one million and please continue the gratifying work.

Comments are closed.