Search code examples
sitecoresitecore6

Traverse Sitecore ancestor items until a template is found


My website contains a number of sublayouts on a single browser layout page placeholder.

I have set one of my sublayouts datasource to a folder within my content structure which contains news items and obtaining its values and subitems as follows for rendering those news items:

Sitecore.Collections.ChildList childItems;

if (Sitecore.Context.Database.GetItem(this.DataSource) != null)
{
  childItems = Sitecore.Context.Database.GetItem(this.DataSource).GetChildren();
}
else
{
  litOutput.Text += "You need to set a datasource";
  return;
}
// Then iterating
foreach (Item item in childItems){}

However I also need to get Sitecore Items that live at the main root of my website which represent other properties and sub items that the sublayout would use.

So really with my datasource defined not only do I iterate down through its children to get the news data (which is working) I then also need to traverse back to the main root and then down a level to a folder called SETTINGS which holds fields for this item.

The main root Template is called "Microsite" so really I need help on how to traverse up until I locate that Template Name and to then go down a level into Settings to obtain these items.

Hope that makes sense and anyone can assist with the approach.


Solution

  • query:./ancestor-or-self::*[@@templatename='Microsite']/*[@@name='Settings']
    

    Although this works, it does not seem like very good coding to do this on every request...

    And you might want to use templateid instead of templatename.. and not 'hardcode' the name "Settings".