Simplifying dates for Blog Archives (Hiding years with 0 posts)

Topics: Writing modules
Oct 5, 2012 at 6:44 PM
Edited Oct 5, 2012 at 6:45 PM

I have a Blog Archives module installed in my sidebar to navigate old press releases and news items. However, there are several years listed with a zero next to them in parentheses because there are no news items from this time frame.

How would you hide the years that don't have news items (i.e. if t, i = 0, show = false)? I know it's a simple question, but I don't know where to look to learn examples of this. Thank you for any advice.

Here's the original code:

@using Orchard.Blogs.Extensions;
@using Orchard.Blogs.Models;
@{
    Style.Require("BlogsArchives");
    Script.Require("BlogsArchives");
    IEnumerable<KeyValuePair<ArchiveData, int>> archives = Model.Archives;
    var dateTimeLocalization = WorkContext.Resolve<Orchard.Core.Shapes.Localization.IDateTimeLocalization>();
    var monthNames = dateTimeLocalization.MonthNames.Text.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
}
<div class="archives">
    @if (archives.Count() > 20) {
    <ul class="years">
        @{
            int lastYear = archives.First().Key.Year;
            int firstYear = archives.Last().Key.Year;
        }
        @for (int year = lastYear; year >= firstYear; year--) {
            var yearMonths = archives.Where(m => m.Key.Year == year);
            
            if (year == lastYear) {
        <li>
            <h4>@year</h4>
             @Html.UnorderedList(yearMonths, (t, i) => Html.Link(string.Format("{0} ({1})", monthNames[t.Key.ToDateTime().Month - 1], t.Value), Url.BlogArchiveMonth((BlogPart)Model.Blog, t.Key.Year, t.Key.Month)), "archiveMonthList")
       </li>
            } 
            
            if (year != lastYear) {
        <li class="previous">
            <h4>@year <span>(@yearMonths.Sum(ym => ym.Value))</span></h4>
            @Html.UnorderedList(yearMonths, (t, i) => Html.Link(string.Format("{0} ({1})", monthNames[t.Key.ToDateTime().Month - 1], t.Value), Url.BlogArchiveMonth((BlogPart)Model.Blog, t.Key.Year, t.Key.Month)), "archiveMonthList")
        </li>
            }
        }
    </ul>
    } 
    else if (archives.Count() > 0) {
        @Html.UnorderedList(archives, (t, i) => Html.Link(string.Format("{0} {2} ({1})", monthNames[t.Key.ToDateTime().Month - 1], t.Value, t.Key.ToDateTime().Year), Url.BlogArchiveMonth((BlogPart)Model.Blog, t.Key.Year, t.Key.Month)), "archiveMonthList")
    }
    else {
    <div class="message info">@T("None found")</div>
    }
</div>
Coordinator
Oct 10, 2012 at 1:25 AM

See that loop over the years in there? Right after it started, it builds an object called yearMonths. You can also see a little after that how the count for a given year is computed: yearMonths.Sum(ym => ym.Value). You could test if that is zero and do continue; if that's the case.