How to render a Blazor component into an HTML string
Asked Answered
E

2

21

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?

Eteocles answered 27/2, 2020 at 16:14 Comment(4)
Now there's an official solution coming with .NET 6: https://mcmap.net/q/660419/-can-we-consume-a-blazor-component-as-a-web-component-within-a-regular-non-blazor-html-page/1768303Hymeneal
@noseratio's link is dead nowInflammation
@Inflammation the link still works for me, but here it is in its full form: #68890311Hymeneal
Works for me now, too. Hrmmm.Inflammation
E
12

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>();  
});
Extensor answered 28/2, 2020 at 18:29 Comment(0)
E
15

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 use in emails. Supports nested components, properties, dependency injection, and can be used in Razor Component libraries.

Erwin answered 11/9, 2021 at 12:52 Comment(2)
Great solution, thanksLynda
Link to official doc : learn.microsoft.com/en-gb/aspnet/core/blazor/components/…Spokeswoman
E
12

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>();  
});
Extensor answered 28/2, 2020 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.