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

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

  • Introduction to .NET Aspire

    Two Microsoft experts will present on the cloud-native application stack designed to simplify the development of distributed systems in .NET at the Visual Studio Live! developer conference coming to Las Vegas next month.

  • Microsoft Previews Copilot AI for Open-Source Eclipse IDE

    Catering to Java jockeys, Microsoft is yet again expanding the sprawling reach of its Copilot-branded AI assistants, previewing a coding tool for the open-source Eclipse IDE.

Subscribe on YouTube

Upcoming Training Events