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

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

  • TypeScript Tops New JetBrains 'Language Promise Index'

    In its latest annual developer ecosystem report, JetBrains introduced a new "Language Promise Index" topped by Microsoft's TypeScript programming language.

Subscribe on YouTube