Copied to clipboard

Flag this post as spam?

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


  • Ferdy Hoefakker 214 posts 248 karma points
    Dec 18, 2012 @ 00:24
    Ferdy Hoefakker
    0

    Playing around with razor

    So, for a personal site, I have been playing around with Razor. But I'm totally not getting it yet.

    I have the following structure:

    website
          news
               year folder
                    month folder
                         news item
                         news item
                    month folder
                         news item

    Now, I am trying to create a script, that will display all the news items on the front page. But for the life of me, I can't get it working.

    foreach(var item in @Model.News)
    {
          foreach(var page in item.children.DescendantOrSelf)
          {
        <li>
         <a class="navigation" href="@page.Url">@page.Name</a>
        </li>
          }
    }

    What am I misunderstanding/doing wrong here?

    -Ferdy

  • Nathan Woulfe 447 posts 1665 karma points MVP 5x hq c-trib
    Dec 18, 2012 @ 05:53
    Nathan Woulfe
    0

    At it's most basic, try something like this, where NewsItem is the document type alias of your news items:

    <ul>
    @foreach (var newsItem in Model.Descendants("NewsItem"))
    {
    <li><a href="@newsItem.Url">@newsItem.Name</a></li>
    }
    </ul>

    There's no need for the outer foreach loop, unless you've got multiple news sections (even then, it's not really needed, depending on how you want to present the page). Also, trying to get descendants of children will fail - descendants is all you need as it includes children. 

    This example simply finds all NewsItems that are descendants of the homepage, and builds the list item accordingly. You'd probably see better performance by first finding the news index page, then getting it's descendant news items, especially if you had a large site with multiple children at the first level. Regardless, my example should get you what you need.

  • Ferdy Hoefakker 214 posts 248 karma points
    Dec 18, 2012 @ 07:03
    Ferdy Hoefakker
    0

    That did the trick. Thanks!

    -Ferdy

Please Sign in or register to post replies

Write your reply to:

Draft