Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a Blazor component into an HTML string

I'm looking for a way to render a Blazor component into an HTML string, so that I'll be able to use it as a templating engine to create and send emails in my web application. Ideas?

like image 616
tocqueville Avatar asked Feb 27 '20 16:02

tocqueville


People also ask

How do I render a Blazor HTML string?

Raw HTML can be rendered in Blazor by using the MarkupString. You can set the raw HTML as a string to any parameter and cast it in a markup string.

How do you render a Blazor component?

To force a component to rerender, use the “StateHasChanged” method in Blazor, to notify that the state has been changed and requires re-rendering.

How do you reference Blazor component in code?

To capture a component reference in Blazor, use the @ref directive attribute. The value of the attribute should match the name of a settable field with the same type as the referenced component. When the parent component is rendered, the field is populated with the child component instance.

Should I render in Blazor?

ShouldRender. This method returns a boolean value, if returns true, it means refresh the UI, otherwise changes are not sent to UI. The ShouldRender method always does the initial rendering despite its return value.


2 Answers

Agua's original answer is still good.. however

A new solution now available for this question: BlazorTemplater is a library I wrote to address this capability (as I needed this for my app!).

This library will render any .razor component to HTML for us in emails. Supports nested components, properties, dependency injection, and can be used in Razor Component libraries.

like image 62
Quango Avatar answered Sep 29 '22 01:09

Quango


Yes, you can use the test library provided by Steve Sanderson and adapt it to your needs.
This article explains how to use it : Introduction to Blazor Component Testing .
The library can be use to generate the HTML of a component.

exemple :

var host = new TestHost();
var component = host.AddComponent<YourComponent>();
var html = component.GetMarkup();

And you can inject services you need.

host.ConfigureServices(services => 
{
   service.AddSingleton<MyService>();  
});
like image 30
agua from mars Avatar answered Sep 29 '22 02:09

agua from mars