How do I write Blazor HTML code inside the @code block?
Version 1
In Blazor idiomatic way would be create component instead of attempting to write HTML directly in the @code
.
Create drawSomething.razor
<p>@Message</p>
@code {
[Parameter]
public string Message {get;set;}
}
and in your Test.razor
@page "/Test"
@if (option == 1)
{
<drawSomething Message="Something" />
}
else
{
<drawSomething Message="Something else" />
}
@code {
int option;
}
Here I assuming that you have something more complex, then just plain
.
Version 2
If you really want easy way, then just
@page "/Test"
@if (option == 1)
{
<p>Something</p>
}
else
{
<p>Something else</p>
}
@code {
int option;
}
Version 3 Based on suggestion from Isaac
@page "/Test"
@if (option == 1)
{
<drawSomething Message="Something" />
}
else
{
<drawSomething Message="Something else" />
}
@code {
int option;
RenderFragment drawSomething(string message)
{
return @<p>@message</p>;
}
}
Update, you can now use:
@GreetPerson("John")
@code {
RenderFragment GreetPerson(string name)
{
return @<p>Hello <em>@name</em></p>;
}
}
Old answer:
This was announced as a feature for Preview6 but it didn't work as advertised then, and some details seem to have changed later. There is a comment from Cosmin Sontu at the bottom of that page that points the right way:
@using Microsoft.AspNetCore.Components.Rendering
@*tested with preview 9*@
@{ GreetPerson(__builder, "John"); }
@code {
void GreetPerson(RenderTreeBuilder __builder, string name)
{
<p>Hello, <em>@name!</em></p>
}
}
The name __builder
cannot be changed. That is a double underscore.