Developer forum

Forum » CMS - Standard features » Recursive Razor function

Recursive Razor function

Adrian Ursu
Reply

Hi Guys,

We have started to use ItemTypes extensiveley and we are facing the following issue:

retrive the values of a field recursively based on the ItemType.

More precisely, we have several tracking codes that are differend based on the structure. We have created an ItemType called Event and each structures will be subordinated to this ItemType. What we need, is to set up some values in some of this ItemType fields and retrive them in all pages that are subordinated.

Something similar with how the WebsiteProperites works but instead of having them only in the root, we want to have them at some point along the structure.

In Umbraco we use to do that with Xslt $currentPage/ancestor-or-self::* [nodeType()='SomeDocumentType'][1]/FieldValue.

Would this be possible with a Razor function? Something that will be a default functionality for DW?

Something like GetItemByItemType("Event") ?

Thanks,

Adrian

 


Replies

 
Mikkel Ricky
Reply

Try something like this:

@functions {
  Dynamicweb.Frontend.Page GetAncestor(string itemType, Dynamicweb.Frontend.Page page = null) {
    if (page == null) {
      page = Pageview.Page;
    }
    while (page != null) {
      if ((string)page.Values["pageitemtype"] == itemType) {
        return page;
      }
      page = Pageview.PageCollection[page.Values["pageparentpageid"]] as Dynamicweb.Frontend.Page;
    }

    return null;
  }

  object GetItemValueFromAncestor(string itemType, string fieldName, Dynamicweb.Frontend.Page page = null) {
    var ancestor = GetAncestor(itemType, page);

    if (ancestor != null && ancestor.Item != null) {
      return ancestor.Item[fieldName];
    }

    return null;
  }
}

@GetItemValueFromAncestor("Event", "SomeField")

Best regards,
Mikkel

 
Adrian Ursu
Reply

Thanks Mikkel,

We have managed to create a function. I was thinking that this can become a standard function inside DW rather than just add it for every project by hand

 

You must be logged in to post in the forum