Adding different CSS classes when using the EPiServer PageTree control

Posted on February 28, 2010 by Frederik Vig in Code Snippet, EPiServer

Another little quick tip. I was browsing the EPiServer World forum and came across a common question.

by David Green

I am using the EpiServer:PageTree control to generate a nested <ul><li> list in the format below.

However I am also using a dropdown menu system called UDM which requires that the class and id “udm” are on the first <ul> tag.

The container object of the PageTree controller exposes the Indent property that we can use for this. Below is a simple example of how to add a CSS class to the first ul in your list (code is based on SubMenu.ascx from the EPiServer Public Templates package).

<%@ Control Language="C#" EnableViewState="false" AutoEventWireup="False" CodeBehind="SubMenu.ascx.cs" Inherits="EPiServer.Templates.Public.Units.Static.SubMenu" %>
<EPiServer:PageTree ShowRootPage="false" runat="server" id="Menu">
    <IndentTemplate>
        <ul <%# AddCssClassToFirstLevel(Container.Indent, "udm") %>>
    </IndentTemplate>
    <ItemHeaderTemplate>
        <li>
    </ItemHeaderTemplate>
    <ItemTemplate>
        <EPiServer:Property PropertyName="PageLink" runat="server" />
    </ItemTemplate>
    <SelectedItemTemplate>
	<EPiServer:Property CssClass="selected" PropertyName="PageName" runat="server" />
    </SelectedItemTemplate>
    <ItemFooterTemplate>
        </li>
    </ItemFooterTemplate>
    <UnindentTemplate>
        </ul>
    </UnindentTemplate>
</EPiServer:PageTree>
using System;
using EPiServer;
using EPiServer.Web.WebControls;
 
namespace EPiServer.Templates.Public.Units.Static
{
    public partial class SubMenu : UserControlBase
    {
        private MenuList _menuList;
 
        /// <summary>
        /// Gets or sets the data source for this control
        /// </summary>
        public MenuList MenuList
        {
            get { return _menuList; }
            set { _menuList = value; }
        }
 
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);
 
            if (MenuList == null)
            {
                return;
            }
            Menu.PageLink = MenuList.OpenTopPage;
            Menu.DataBind();
        }
 
        protected string AddCssClassToFirstLevel(int level, string cssClassName)
        {
            if (level == 1)
            {
                return string.Format("class=\"{0}\"", cssClassName);
            }
 
            return string.Empty;
        }
    }
}

We can easily add more complex logic. We also have access to the HasChildren property, which tells us if the active page has any children.

Hope this helps.

Related Posts: