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">
    <thead>
        <tr>@TableHeader</tr>
    </thead>
    <tbody>
        @foreach (var item in Items)
        {
            <tr>@RowTemplate(item)</tr>
        }
    </tbody>
    <tfoot>
        <tr>@TableFooter</tr>
    </tfoot>
</table>

@code {
    [Parameter]
    public RenderFragment TableHeader { get; set; }

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

    [Parameter]
    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">
    <TableHeader>
        <th>Date</th>
        <th>Temp. (C)</th>
        <th>Temp. (F)</th>
        <th>Summary</th>
    </TableHeader>
    <RowTemplate Context="forecast">
        <td>@forecast.Date.ToShortDateString()</td>
        <td>@forecast.TemperatureC</td>
        <td>@forecast.TemperatureF</td>
        <td>@forecast.Summary</td>
    </RowTemplate>
</TableTemplate>

@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)]
        }).ToArray();
    }
}

Share with

Related FAQs

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

Please submit your question and answer.