Find Closest Ancestor Method

0
Comments
3
Votes
Login to vote

The find closest ancestor method is a handy method that recursively traverses up the tree from a given node until it finds a document with the class type you have specified. For example you might have news items that live under various page menu items in order to categorize them (e.g. Tech News, Global News, etc.) and you want to display the section name (page menu item's title) above the news title on the news item. You can use the find closest ancestor method to get the page menu item that is above the current news item and display the page menu item's title.

Here is the find closest ancestor method:

/// <summary>
/// Recursively traverse up the tree from the specified node until it finds a node with the specified class type
/// </summary>
/// <param name="currentNode">The starting node.</param>
/// <param name="className">The class type to look for.</param>
/// <returns></returns>
public static TreeNode FindClosestAncestor(TreeNode currentNode, string className)
{
    if (currentNode == null)
        return null;

    if (currentNode.NodeClassName.ToLower() == className.ToLower())
        return currentNode;

    return FindClosestAncestor(TreeHelper.SelectSingleNode(currentNode.NodeParentID), className);
}
 

You can create a shortcut method that uses the current document:

public static TreeNode GetClosestAncestorFromCurrent(string className)
{
    return FindClosestAncestor(CMSContext.CurrentDocument, className);
}

If you place these methods in a class called _Functions in your App_Code folder you can use the previous method to display the page's title:

<%=_Functions.GetClosestAncestorFromCurrent("CMS.MenuItem").DocumentName%>

Download

You can download a copy of the _Functions.cs file here.

 
Posted by Ryan Williams on 10/15/2010 1:47:17 PM
  
Comments
Blog post currently doesn't have any comments.