0
votes

Here is my case:

I have a component Foo and I want it to have a blazor template called Wrapper which will be used to wrap somepart of Foo's content.

What I need to do is something like

Normal usage:

<Foo>
    <Wrapper>
        <div>
            <p>Something in the wraper</p>
            @context // context should be some content of Foo
        </div>
    </Wraper>
</Foo>

Inside Foo

@* Other content of Foo*@

@if(Wrapper != null){
    @* Pass to Wrapper some content of Foo *@
    Wrapper(@* How to render html/components here? *@)
}

@* Other content of Foo*@

But there is no way to pass html or components for the template?

How can I do this?

1
I am not sure I understand your question very well. Are you talking about ChildContent? (You may also be interested in Templated controls?) - Chanan Braunstein
I will try to elaborate more my question, but what is a templated control? - Vencovsky
@ChananBraunstein the docs explain about Templated Components, which it different from Templated controls. Also, the docs don't have an example where you have a RenderFragment<RenderFragment> - Vencovsky

1 Answers

4
votes

Your Wrapper in this case is a RenderFragment that you want to accept another RenderFragment, so it's signature would be

[Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}

Here is the complete Foo.razor

@* Other content of Foo*@
<h1>This is Foo</h1>

@if(Wrapper != null){
    @* Pass to Wrapper some content of Foo *@
    @Wrapper(
        @<h2>This comes from Foo</h2>
    )
}

<h1>There is no more Foo</h1>

@code 
{
    [Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}
}

Notice carefully the construct inside the call to Wrapper.

  1. Start with @Wrapper so this is a call from Razor

  2. The open ( after Wrapper puts you back in C# land, so -

  3. use @ to swap back to Razor code.

  4. Now you can use Razor/HTML markup <h2>This comes from Foo</h2>

  5. Close the call to Wrapper with a )

That is how you can use a RenderFragment that takes a RenderFragment as it's context.

The output from this would be

This is Foo

Something in the wraper

This comes from Foo

There is no more Foo

You can test it out here https://blazorfiddle.com/s/ox4tl146