0

I have a navigation component that should list the current page in a hierarchy of items. I use below line of code to build navigation tree.

return item
       .GetChildren()
       .Select(i => new NavigationMenuItem
       (
          title: i.DisplayName,
          url: i.Url,
          children: i.IsAncestorOrSelf(current) ? Build(i, current) : null
       ));

Problem is some pages has other items as children I need to only return page-children when calling .GetChildren(), so how is that possible?

1
  • What about checking if item has Layout? Something like i.Visualization.Layout != null?
    – Marek Musielak
    Commented Jul 2, 2018 at 12:52

2 Answers 2

2

In case you need to filter only on the item template without worrying about other templates that are inherited by your item template you can use the following:

item
  .GetChildren()
  .Where(w => w.TemplateID == templateId) //filter on children's TemplateId
  .Select(i => new NavigationMenuItem
  (
   title: i.DisplayName,
   url: i.Url,
   children: i.IsAncestorOrSelf(current) ? Build(i, current) : null
  ));

However, if you need to filter on derived templates (templates inherited by the item template), you can use this:

item
  .GetChildren()
  .Where(w => w.Template.BaseTemplates.Any(a => a.ID == derivedTemplateId))
  .Select(i => new NavigationMenuItem
  (
   title: i.DisplayName,
   url: i.Url,
   children: i.IsAncestorOrSelf(current) ? Build(i, current) : null
  ));
2

You can create a base page template and inherit this template to all pages type, then filter where the item is derived from the page template

public static bool IsDerived(this Item item, ID templateId)
    {
        if (item == null)
            return false;

        return !templateId.IsNull && item.IsDerived(item.Database.Templates[templateId]);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.