blazor

Convert string to RenderFragment


I'm wondering if there's a recommended way of converting string to RenderFragment in code. Now I'm doing this:

RenderFragment fragm = @<text>@myString</text>;

but I don't know if this is the best way to do it


Solution

  • There is no "recommended" method that I know of.

    A RenderFragment is a delegate defined as:

    public delegate void RenderFragment(RenderTreeBuilder builder);
    

    It's a block of code passed to the Renderer to actually render the component markup.

    Here's a demo page that shows three ways to define one:

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    <div class="p-2">
        @RF1
    </div>
    <div class="p-2">
        @RF2
    </div>
    <div class="p-2">
        @RF3
    </div>
    
    @code {
        //need to be careful with the builder name not to clash with one the names used by the Razor compiler
        private RenderFragment RF1 => (mybuilder) =>
            {
            <text>@myString</text>
            };
    
        private RenderFragment RF2 => (builder) =>
            {
                builder.AddMarkupContent(0, $"<text>{myString}</text>");
            };
    
        // DO NOT use an loop incrementer for the sequence number
        private RenderFragment RF3 => (builder) =>
            {
                builder.OpenElement(0, "text");
                builder.AddContent(1, myString);
                builder.CloseElement();
            };
    
        private string myString = "Hello Blazor";
    }
    

    The first one is a little counterintuitive. It only works in a Razor component file because the Razor compiler recognises it and compiles it into a code block similar to the second example.