Jackal
Jackal

Reputation: 3521

How to render content inside a razor component in blazor?

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>

Upvotes: 9

Views: 6191

Answers (2)

Gopa
Gopa

Reputation: 354

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

Upvotes: 17

TheLegendaryCopyCoder
TheLegendaryCopyCoder

Reputation: 1832

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>

Upvotes: 1

Related Questions