Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

html - How to avoid additional whitespaces and " " being inserted in render tree in Blazor

For following example codes

<div>
    @for (int i = 0; i < 10; i++)
    {
        <span class="@classes[i]">@i</span>
    }
</div>

What I want to display is (with each character in different style)

01234567890

but what actually display is (additional whitespace between each characters)

0 1 2 3 4 5 6 7 8 9

I use ILSpy to investigate what happens in the render tree, and found following

        __builder.OpenElement(2, "div");
        __builder.AddMarkupContent(3, "
");
        for (int i = 0; i < 10; i++)
        {
            __builder.AddContent(4, "        ");
            __builder.OpenElement(5, "span");
            __builder.AddAttribute(6, "class", classes[i]);
            __builder.AddContent(7, i);
            __builder.CloseElement();
            __builder.AddMarkupContent(8, "
");
        }
        __builder.CloseElement();

The sequence 4 adds additional whitespaces and sequence 8 adds " ", which I believe is the reason of the additional whitespace between characters.

I could mitigate the issue by writing in this way

<div>@for (int i = 0; i < 10; i++)
{<span class="@classes[i]">@i</span>}
</div>

However, when there are more and different contents in the same line, the code would be very long. Also when I press Ctrl+D to format the document, in some scenarios VS would "fix" the code in wrong way.

I would like to see if there's any better suggestion for this issue. I thought about following (but couldn't find solution yet)

  1. Use CSS to ignore whitespaces and between spans
  2. Somehow add extra @{} to help formatting.
  3. Some magic parameter to avoid whitespaces and added to the render tree.
question from:https://stackoverflow.com/questions/65545778/how-to-avoid-additional-whitespaces-and-r-n-being-inserted-in-render-tree-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess you are still using aspnetcore 3.x, as this was fixed in .NET5.

Try it in a .NET5 Blazor project - it should work fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...