C# Corner

An Introduction to Templated Components in Blazor

In this article I'm going to introduce you to templated components and show how you can take advantage of them in your Blazor projects. Templated components were introduced in the 0.6.0 release of Blazor and are made up of three features: template parameters, template context parameters and generic-typed components. I'm going to cover these three areas over a few examples so I can show you how they all fit together.

What Are Templated Components?
Templated components expose customizable sections via parameters. Consumers then pass in their own templates for these sections that the component will use when rendering.

So what does this look like to use?

Let's dive straight in and create a simple templated component and find out:

FilmList.cshtml:

<div>
  @foreach (var film in Films)
  {
    @FilmTemplate(film)
  }
</div>

@functions {
  [Parameter] RenderFragment FilmTemplate { get; set; }
  [Parameter] IReadOnlyList Films { get; set; }
}

Usage:

<FilmList Films="@Films">
  <FilmTemplate>
    <div>@context.Title (@context.YearReleased)</div>
  </FilmTemplate>
</FilmList>

@functions {
  public List Films { get; set; } = new List {
    new Film("Pulp Fiction", "1994", "pulp-fiction.jpg"),
    new Film("Bad Boys II", "2003", "bad-boys2.jpg"),
    new Film("The Fast and the Furious", "2001", "tfatf.jpg"),
    new Film("The Greatest Showman", "2017", "greatest-showman.jpg")
  };
}

I've defined a simple FilmList component that just loops over the films that have been passed in. The key difference here is that the FilmTemplate property is a template parameter. Template parameters are what make templated components different from normal components.

Template parameters allow you to define an area of the component that will use a template provided by the component consumer when rendering. They can be defined as either RenderFragment or RenderFragment <T>. I'll cover the generic version in a bit.

In order to use the FilmList component we have to define a template for the film. This is done using elements that match the template parameter name, in our case <FilmTemplate></FilmTemplate>.

Inside these template elements we have access to a special property called context. This is derived from the type of the template parameter, in our case Film. This allows us full IntelliSense when defining our template. We can even change it to make our code easier to understand. It would make more sense here to rename it to film, and we can do that as follows:

<FilmTemplate Context="film">
  <div>@film.Title (@film.YearReleased)</div>
</FilmTemplate>

Making Things a Bit More Generic
We now know a bit more about templated components and we have created our first one. But let's face it, it's not going to save us much time and there's no reuse outside of displaying films. What if I wanted to display a list of motorbikes? Now I'm going to have to create whole new component! Actually, no. Say hello to generic-typed components.

Using the code above as starting point, I'm going to make some changes to make a more reusable component:

List.cshtml:

@typeparam TItem

<div>
  @foreach (var item in Items)
  {
    @ItemTemplate(item)
  }
</div>

@functions {

  [Parameter] RenderFragment<TItem> ItemTemplate { get; set; }
  [Parameter] IReadOnlyList<TItem> Items { get; set; }
}

Usage:

<List Items="@Films">
  <ItemTemplate>
    <div>@context.Title (@context.YearReleased)</div>
  </ItemTemplate>
</List>

When defining the List component I've used the new @typeparam directive. It's this directive that makes the component generic. I've specified a type parameter, TItem, which I can now use in my component. I'm also now using RenderFragment<T>, which I mentioned earlier, to define my template parameter.

In terms of usage, other than changing the component name and the template element name, everything is the same. I'm also still getting IntelliSense when I'm defining my template, because Blazor will try and derive the types for you.

However, it is worth noting that this is not always possible. If you hit this scenario you can tell Blazor the type by using an attribute matching the name of the type parameter specified in your component, like so:

<List Items="@Films" TItem="Film">
  <ItemTemplate>
    <div>@context.Title (@context.YearReleased)</div>
  </ItemTemplate>
</List>

Wrapping Up
As you can see, templated components are a fantastic addition to the toolbox of any Blazor developer. They make it really easy to create some high-level reusable components, especially when incorporating generics.

About the Author

Chris Sainty is a lead software engineer at Flagship Group, a housing association based in Norwich, Norfolk (UK). He leads a team in developing in-house repairs management software using a wide range of technologies. Chris is passionate about Web technologies and ASP.NET Core in particular. He loves sharing knowledge and writes regular posts on his blog at https://codedaze.io.

comments powered by Disqus

Featured

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube