Quickly render Razor components to strings and TextWriters.
Install-Package RazorString
It should start out looking something like this:
<ProjectSdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReferenceInclude="Microsoft.AspNetCore.Components.Web"Version="8.0.3" />
</ItemGroup>
</Project>
The important things are that:
- Is is a
Microsoft.NET.Sdk.Razorproject - It references
Microsoft.AspNetCore.Components.Web
Get creative! You can keep things simple or complex.
Here's a fun example.
Create a file named Composite.razor:
Hello@Context.Name! I see that you were born on @Context.Date_Of_Birth.
Today we will eat:
Breakfast: @Breakfast
Lunch: @Lunch
Dinner: @Dinner
@code {[Parameter]publicrequiredCompositeContextContext{get;init;}[Parameter]publicrequiredstringBreakfast{get;init;}[Parameter]publicrequiredstringLunch{get;init;}[Parameter]publicrequiredstringDinner{get;init;}}Then also create a file named CompositeContext.cs:
namespaceExample.Templates{publicrecordCompositeContext{publicrequiredstringName{get;init;}publicrequiredDateTimeDate_Of_Birth{get;init;}}}varTemplate=TemplateFactory.Default.FromComponent<Composite>().WithParameters([("Breakfast","Coffee"),("Lunch","Sandwich"),("Dinner","Pizza"),("Context",newCompositeContext(){Name="John Smith",Date_Of_Birth=newDateTime(1901,01,01),})]);varContent=awaitTemplate.RenderAsync();Console.WriteLine(Content);If your Razor templates have a property named Context:
@code{[Parameter]publicrequiredCompositeContextContext{get;init;}}You can pass in that argument with:
varTemplate=TemplateFactory.Default.FromComponent<Composite>().WithContext(newCompositeContext(){Name="John Smith",Date_Of_Birth=newDateTime(1901,01,01),});If you're going to use the same template in a loop, reuse it:
varTemplate=TemplateFactory.Default.FromComponent<Composite>();foreach(variteminDataSet){varDerived=Template.WithParameters([("Breakfast",item.Breakfast),("Lunch",item.Lunch),("Dinner",item.Dinner),("Context",newCompositeContext(){Name=item.Name,Date_Of_Birth=item.DoB,}),]);varContent=awaitDerived.RenderAsync();Console.WriteLine(Content);}You don't have to provide all the args at once and you can override values.
//Load our base template with no argsvarEmptyTemplate=TemplateFactory.Default.FromComponent<Composite>();//Set some valuesvarTemplateWithDefaults=EmptyTemplate.WithParameters([("Context",newCompositeContext(){Name="John Smith",Date_Of_Birth=newDateTime(1901,01,01),}),("Breakfast","Coffee"),]);foreach(varMealinMeals){varMealPlan=TemplateWithDefaults.WithParameters([("Breakfast",Meal.Breakfast),//Override the default ("Lunch",Meal.Lunch),("Dinner",Meal.Dinner),]);varContent=awaitMealPlan.RenderAsync();Console.WriteLine(Content);}