Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Drew DeVault 22 posts 43 karma points
    Oct 13, 2011 @ 20:34
    Drew DeVault
    0

    Finding the first parent of a certain type

    Hello,

    If I wanted to traverse up the tree in a razor script until I found a parent node of the type Region, how would I do this?

    My solution works, but not if there are several Regions at the same level:

    var startNode = @Model.AncestorOrSelf().Regions.First();

     

  • Keith Petersen 67 posts 111 karma points
    Oct 17, 2011 @ 19:40
    Keith Petersen
    0

    Maybe with a Where filter?

    @Model.AncestorOrSelf().Where("Name.Contains(\"region\"");

    Haven't tested this-- it's just an idea.

  • Drew DeVault 22 posts 43 karma points
    Oct 17, 2011 @ 19:51
    Drew DeVault
    0

    Thanks Keith,

    That would correctly get regions, but would encounter the same issue with not getting the parent of the current node.

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Oct 17, 2011 @ 21:33
    Dan Diplo
    3

    I may be missing what you are trying to do, but this sounds like what you need:

    @Model.AncestorOrSelf("Region");
  • Drew DeVault 22 posts 43 karma points
    Oct 17, 2011 @ 21:41
    Drew DeVault
    0

    That worked out perfectly!  Thanks.  Can you explain why it works that way?  I can't find documentation anywhere.

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Oct 17, 2011 @ 22:09
    Dan Diplo
    1

    Basically AncestorOrSelf() has a number of overloads, one of which takes a a NodeTypeAlias parameter, which will only returns nodes of that type. In this case it will walk up the tree until it finds the first node with an alias of Region.

    Proper Razor documentation is pretty thin, as you noted. The best place to find some is at http://our.umbraco.org/wiki/reference/code-snippets/razor-snippets

    If you are using Visual Studio to edit your Razor files then a tip I use is to type @CurrentModel instead of @Model and you should get intellisense that displays all the methods availale on DynamicNode (which is the actual type of Model). But if you want to reference custom properties you still need to use @Model as these are only available on dynamic types.

  • Drew DeVault 22 posts 43 karma points
    Oct 17, 2011 @ 22:11
    Drew DeVault
    0

    Thanks for clarifying, I appriciate it.

  • Keith Petersen 67 posts 111 karma points
    Oct 17, 2011 @ 22:16
Please Sign in or register to post replies

Write your reply to:

Draft