Rendering an Item's Children

Blog | Technical
Written By: Nabil OrfaliPublished On: Jul 05 2016

Getting the Item's Children

Getting an item's children is a basic but important piece of logic that is used frequently within Sitecore. 

Let's say you have an item "A", which has two children, items "B" and "C", and you want to display links to items B and C from item A. In this article, we will explore how to do that.

Start by creating a Sublayout and binding it to a placeholder (see the article "Layouts, Sublayouts, and Placeholders" for more details). 

To retrieve the item's children, navigate to your Sublayout's code behind file (.ascx.cs) in the Visual Studio Solution Explorer and add the following code to the Page_Load function:

TheRepeaterID.DataSource = Sitecore.Context.Item.GetChildren();
TheRepeaterID.DataBind();

What we are doing is that we are first getting the item's children and binding the data to a repeater, which we will create and reference in the Sublayout's file as show here:

<asp:Repeater ID="TheRepeaterID" ItemType="Sitecore.Data.Items.Item" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="HyperLink1" Text="<%#: Item.Name %>" NavigateUrl="#" runat="server" />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>

Getting the Children's Links

The repeater will render the item's children, but without the links. We can add the links by simply replacing NavigateUrl="#" with:

NavigateUrl="<%#: Sitecore.Links.LinkManager.GetItemUrl(Item, new Sitecore.Links.UrlOptions { UseDisplayName = true }) %>"

Master this process and you're well on your way to being a Sitecore professional developer.

About the AuthorNabil Orfali
Nabil OrfaliCEO & Founder, Sitecore Strategy MVP
Loading...