Umbraco macro

A common task in Umbraco is to create a nan menu or site map.  Writing the necessary code to traverse the nodes of the website can quickly become over complex and inflexible.  Today I had to do write such a macro for the first time and did not find a straight forward example so thought it would be worth sharing what I came up with.  It is a fairly simple razor script that achieves infinite level traversal using a very flexible and easy to read.  This helper is the core of what I came up with:

 

This helper, when passed a parent node, uses recursion to infinitely traverse children nodes.  If you want to limit the depth of the traversal, just modify it like this and use a macro parameter to specify the maximum depth:

You can use other properties on the node to control which nodes’ children will traverse.  For example, I have added a property “Hide children pages from navigation” to specify a parent whose children should not be traversed for navigation.  I then simply modified the recursion call to have this conditional statement:

This is a straight forward way of making a site map or navigation menu in a Umbraco macro and, since I didn’t find many examples, I hope it helps someone else.