Using Recursion

Using Recursion

Controls featured in this example:

  • Sitecore Web Control
  • XSLT Rendering

Classes featured in this example:

  • Sitecore.Context
  • Sitecore.Data.Items.Item

Using Recursion C# Web Control Code

Sitecore.Data.Items.Item item = this.GetItem();
if (item == null) return;

Sitecore.Data.Items.Item home = GetHomeItem(item);
if (home == null) return;

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("C# Web Control Real-time Output");
output.RenderEndTag(); //Div

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
string displayName = Sitecore.StringUtil.GetString(item.DisplayName, item.Name);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", displayName);
output.RenderEndTag(); //P

output.Write("{0}&#58;&#160;{1}", "Home Title", "<b>" + home["title"] + "</b>");
output.RenderEndTag(); //Div

  private static Sitecore.Data.Items.Item GetHomeItem(Sitecore.Data.Items.Item item)

{
  if (item == null || item.Key.Equals("home"))
  {
    return item;
  }

  else
  {
    return GetHomeItem(item.Parent);
  }
}

Using Recursion XSLT Rendering Code

<xsl:variable name="home" select="$sc_currentitem/ancestor-or-self::item[@key='home']" />

<div style="font-weight:bold; width:100%; clear:both"> <br/>
<xsl:value-of select="'XSLT Rendering Real-time Output'"/>
</div>

<div style="font-size:x-small; width:100%; clear:both">
<p><b><xsl:value-of select="'Item: '" /><sc:text field="title" select="$sc_item" /></b></p>

<p>Home Title: <b><sc:text field="title" select="$home" /></b></p>
</div>


Using Recursion C# Web Control Output

Home Title: Resources for Sitecore Users


Using Recursion XSLT Rendering Output

Home Title: Resources for Sitecore Users

Notes

  • Recursive methods walk up the ancestor portion of the tree to find an item, such as the site root of the current item
  • The xslt @key requires the lowercase name of the home item