How to re-use a mark up wrapper in Blazor, without creating another component

Viewed 112

This is what i'm trying to do

<h3>Component</h3>

@Wrapper(@<span>Content One</span>)
@Wrapper(@<span>Content Two</span>)
@Wrapper(@<span>Content Three</span>)

@code {
    RenderFragment Wrapper(RenderFragment content)
    {
        <h2>Check this out: @content</h2>
    }
}

output should be:

<h2>Check this out: <span>Content One</span></h2>
<h2>Check this out: <span>Content Two</span></h2>
<h2>Check this out: <span>Content Three</span></h2>

But it won't compile.

I don't want to have to create a separate component for the wrapper, although I know this can be done, the wrapper is far too simple to justify having another file to maintain.

2 Answers

This is the right syntax, in your scenario, you should to define a RenderFragment that receives one RenderFragment parameter, like this:

@page "/"

@Wrapper(@<span>Content One</span>)
@Wrapper(@<span>Content Two</span>)
@Wrapper(@<span>Content Three</span>)

@code {
    protected RenderFragment<RenderFragment>  Wrapper = content => __builder =>
    {
        <div>
            Check this out: @content
        </div>   
    };
}

Running:

enter image description here

RenderFragment is a delegate and you need to use like below. I have slightly modified implementation to take only content one, content two , etc as input.

<h3>Component</h3>

@Wrapper("Content One")
@Wrapper("Content Two")
@Wrapper("Content Three")


@code {    

 RenderFragment Wrapper(string content) => builder =>
        {
            builder.OpenElement(0, "h2");
            builder.AddContent(1, "Check this out:");
            builder.OpenElement(2, "span");
            builder.AddContent(3, content);
            builder.CloseElement();
            builder.CloseElement();
        };
}

you can give it a try here snippet

Related