Convert string to RenderFragment
Asked Answered
O

2

6

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

Orchid answered 9/3, 2022 at 11:10 Comment(2)
You might read about the wig-pig syntax (down the page...) @:@{place some code here};Germinal
That is a decent way to create a RenderFragment, but why? You can use the string anywhere you use the fragment - there is no benefit I can see.Exterminate
S
10

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.

Sick answered 10/3, 2022 at 7:58 Comment(0)
L
0

I found (MarkupString) was the cast I needed to display my html string as markup.

Latria answered 22/8 at 1:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.