I am currently experimenting with templated components in Blazor. I am trying to set up a component with a RenderFragment
parameter.
For example:
<div>
@this.Content
</div>
@code {
[Parameter]
public RenderFragment? Content { get; set; }
}
When I use it on a Razor page, it looks like this:
<MyComponent>
<Content>
</Content>
</MyComponent>
I'd prefer not having to add the <Content>
tag every time, but have everything inside the component brackets be the content.
Is there a way to achieve my preferred behavior?
I looked up different ways to pass parameters to a component, but I haven't quite figured out how to remove the need for the additional tags.
EDIT: The answer was naming the parameter "ChildContent".
If you give your RenderFragment
parameter any other name (e.g. Content
), you have to wrap it in a <Content>…</Content>
tag. Rename your parameter to ChildContent
, and you can omit the extra tag entirely:
<!-- MyComponent.razor -->
<div>
@ChildContent
</div>
@code {
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
Then you can consume it simply as:
<MyComponent>
<p>This paragraph is rendered inside the component.</p>
<AnotherComponent />
</MyComponent>
No <ChildContent>
wrapper needed.