Live Chat Icon For mobile
Live Chat Icon

How do you create a template component in Blazor?

Platform: Blazor| Category: Templated components

Blazor supports templated components. These are components that accept one or more UI templates as parameters and these parameters can be used for component rendering.

A templated component can be created by using one or more component parameters of type RenderFragment or RenderFragment<T>. The RenderFragment is a part of the UI that is rendered by the component. It may have parameters that are used during the rendering of the component or while the RenderFragment is invoked.

Table template component

<table class="table">
        @foreach (var item in Items)

@code {
    public RenderFragment TableHeader { get; set; }

    public RenderFragment<WeatherForecast> RowTemplate { get; set; }
    public RenderFragment TableFooter { get; set; }

    public WeatherForecast[] Items { get; set; }

When using a templated component, the template parameters can be specified using child elements that match the names of the parameters (TableHeader and RowTemplate in the following example).

<TableTemplate Items="@forecasts">
        <th>Temp. (C)</th>
        <th>Temp. (F)</th>
    <RowTemplate Context="forecast">

@code {
    WeatherForecast[] forecasts;

    protected override void OnInit()
        forecasts = WeatherForecasts();

    public WeatherForecast[] WeatherForecasts()
        string[] Summaries = new[]
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.