Groups

Turn tags, categories, dates and flags into group datasets, generate typed group pages, and write custom groupers.

On this page
csharp
[DataSource("Posts", "./*.md", OrderBy = "Date desc, Title")]
public sealed record BlogPost(
    string Slug, string Title,
    [GroupBy("Tags")] string[] Tags,
    [GroupBy("Categories")] string Category,
    [GroupByDate("Archive", GroupPeriod.Month)] DateOnly Date,
    [GroupByFlag("Highlights", "Featured", "More posts")] bool Featured);

Put a grouping attribute on a property. Bevel builds a dataset of groups from it, such as tags, categories or an archive by month.

Map a page per group

Groups hang off the dataset they come from. Map one page per group like any other items:

csharp
app.MapStatic<TagPage>("/tags/{Slug}", (ISiteData data) => data.Posts.Tags);
app.MapStatic<CategoryPage>("/categories/{Slug}", (ISiteData data) => data.Posts.Categories);

Each group has Text, Slug, Count, Keys and Items. Items are the same instances as data.Posts. A page takes the generated type, such as BlogPostGroups.Tag:

razor
@code {
    [Parameter, EditorRequired] public BlogPostGroups.Tag Tag { get; set; } = default!;
}

data.Posts is still a list of posts. It is a generated PostsCollection that also has the group properties.

Use Links.To(group), so slugs and date formats always match. Do not build the URL from the text yourself.

razor
@foreach (var tag in Data.Posts.Tags.Where(t => Post.Tags.Contains(t.Text)))
{
    <a href="@Links.To(tag)">#@tag.Text</a>
}

To go from a post to its category, find the group that holds it: Links.To(Data.Posts.Categories.First(c => c.Items.Contains(Post))).

Pick an attribute

[GroupBy("Tags")] takes a string, string?, string[], IReadOnlyList<string>, IEnumerable<string> or List<string>. The value is the text. Default OrderBy: Count desc, Text.

Text groups trim values, skip empty ones, and merge values that have the same slug. Text is the first spelling Bevel finds. Spellings that differ only in case or spacing merge silently. Spellings that differ in other ways but share a slug (Node.js and Node js) merge too, with warning BEVEL077 that lists them.

Numbers, enums and other types need a custom grouper. A property of the wrong type for its attribute fails the build and names the attribute to use.

Options shared by all attributes

  • TypeName: the generated type name. Defaults to the singular of the name (Tags becomes Tag, Categories becomes Category, Archive stays Archive).
  • Key: the member that identifies an item. Defaults to Slug, then Id. Keys must be unique in the parent, ignoring case.
  • Source: the parent dataset. Only needed when the item type belongs to several datasets.
  • OrderBy: Text, Slug, Value and Count, each with an optional asc or desc.

A member declares its grouping attribute in one place: on the property, or on constructor parameters. A positional record declares it on the parameter. If a member has the attribute on both, or on several constructors with different options, the build fails with BEVEL076. The same attribute repeated identically on several constructors counts once. [Reference] follows the same rule (BEVEL078).

What gets generated

For a BlogPost dataset named Posts with Tags and Categories groups:

csharp
public static partial class BlogPostGroups
{
    public sealed partial record Tag : Group<BlogPost, string>;
    public sealed partial record Category : Group<BlogPost, string>;
}

public sealed partial class PostsCollection : IReadOnlyList<BlogPost>
{
    public IReadOnlyList<BlogPostGroups.Tag> Tags { get; }
    public IReadOnlyList<BlogPostGroups.Category> Categories { get; }
}

public partial interface ISiteData
{
    PostsCollection Posts { get; }
}

Group<TItem> has Text, Slug, Keys, Items and Count. Group<TItem, TValue> adds a typed Value. The snapshot stores keys and values only. Items are linked to the instances in the parent list when the group is first used. Each group is read on first access.

The data graph names a group dataset Posts.Tags. A loader that needs it declares [DependsOn("Posts.Tags")] and reads context.Get<IReadOnlyList<Group<BlogPost>>>("Posts.Tags").

Slugs

BevelSlug.Slugify keeps letters and digits, removes accents and turns every other run of characters into one dash. It also spells out three symbols so common names stay distinct: # becomes sharp, + becomes plus and & becomes and. C# is c-sharp, C++ is c-plus-plus and R&D is r-and-d. ASP.NET Core is still asp-net-core. Text that has no letters or digits becomes item.

Custom groupers

For anything else, write a grouper. It returns zero or more keys for a value:

csharp
public interface IGrouper<in TValue, TGroupValue>
{
    IEnumerable<GroupKey<TGroupValue>> GetGroups(TValue value);
}

public readonly record struct GroupKey<TGroupValue>(TGroupValue Value, string Text, string? Slug = null);
csharp
public sealed class ReadingTimeGrouper : IGrouper<int, ReadingTime>
{
    public IEnumerable<GroupKey<ReadingTime>> GetGroups(int minutes)
    {
        var size = minutes <= 3 ? ReadingTime.Quick : ReadingTime.Long;
        yield return new(size, size == ReadingTime.Quick ? "Quick reads" : "Long reads");
    }
}

public sealed record BlogPost(..., [GroupBy<ReadingTimeGrouper>("ReadingTimes")] int ReadingMinutes);
  • Return zero keys to leave a value ungrouped, or several to put it in several groups. For a collection property, GetGroups runs once per element. Null values are never passed in.
  • Slug defaults to the slug of Text. Keys with the same slug merge, and the first Text and Value win. Two different values with one slug, or an empty Text, fail the build.
  • A grouper that implements IDisposable or IAsyncDisposable is disposed after grouping, even when grouping fails.
  • Bevel creates one grouper per attribute with the Build-time services, so constructor dependencies come from your IBevelDataStartup. The type must be declared under Data/.

Names

Group names are properties of the parent collection. They must be unique within the parent and cannot be Count, Item, GetEnumerator or an object member name. The names <Item>Groups and <Dataset>Collection are namespace-level and are checked against ISiteData, SiteData and your own types.