How to render content inside a razor component in blazor?
Asked Answered
A

2

9

With tag helpers you could define an area where you could easily write content. For example, i could make a bootstrap card tag helper and easily render whatever i want inside the card body tag. With razor components how can i achieve this?

<div class="card">
    <div class="card-header"></div>
    <div class="card-body">

        @*render content here*@

    </div>
</div>
Athena answered 10/3, 2020 at 21:40 Comment(0)
T
17

Templated components can be implemented using a class called RenderFragment. They are implement same like a parameter property but they capture the content declared inside the component tags.

Below is an example from the default Blazor project. I updated the SurveyPrompt component to take in the question content like this

<div class="alert alert-secondary mt-4" role="alert">
    <span class="oi oi-pencil mr-2" aria-hidden="true"></span>
    <strong>@Title</strong>

    <span class="text-nowrap">
       @ChildContent
        <a target="_blank" class="font-weight-bold" href="https://go.microsoft.com/fwlink/?linkid=2127996">brief survey</a>
    </span>
</div>
   
@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

Here is how i pass the content to the Survey component

<SurveyPrompt Title="How is Blazor working for you?">
     <i class="carousel-control-next-icon"></i>Please take our survey below
</SurveyPrompt>

You can also have the RenderFragment typed, read more about it here: https://learn.microsoft.com/en-us/aspnet/core/blazor/templated-components?view=aspnetcore-3.1

Tawny answered 11/6, 2020 at 23:31 Comment(0)
W
1

Just to add to Gopa's answer. You can also use multiple RanderFragment properties and specify the property name as the HTML tag to distinguish between them.

@*StoryComponent*@

<div>
 <span>@this.Title</span><br>
 <span>@this.Body</span>
</div>

@code {
    [Parameter] public string Title { get; set; }
    [Parameter] public string Body{ get; set; }
}

Usage would be:

<StoryComponent>
  <Title>Title ABC</Title>
  <Body>Body 123</Body>
</StoryComponent>
Willyt answered 15/11, 2023 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.