Razorengine has been used as runtime html packager but seemingly the maintenance and support has been stopped for a year.
I have looked into a few and currently Scriban seems to be the right fit. However before putting this into the solution, I want to make sure if Microsoft does not have their own library instead of no-guarantee in maintenance 3rd party ones.
or can I only make the minimal necessary features from razor work just to achieve creating html runtime using razor binding? For example, by adding a few references..
If you need to create a template service based on the ASP.NET Core
RazorEngine
you can do get all needed services via DI
:
public TemplateService(IRazorViewEngine viewEngine, IServiceProvider serviceProvider, ITempDataProvider tempDataProvider)
{
_viewEngine = viewEngine;
_serviceProvider = serviceProvider;
_tempDataProvider = tempDataProvider;
}
Register in DI
in your Startup
class:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<ITemplateService, TemplateService>();
// ...
}
And then you can get access to ITemplateService
by enjecting it to constructor of your Controller
class or other service. And use Views
and ViewModels
to generate HTML
using RenderTemplateAsync
method See the implementation details here:
public async Task<string> RenderTemplateAsync<TViewModel>(string viewFilename, TViewModel viewModel)
{
// ... see the details by the link above
}
So the call in Controller
might look like this:
var htmlContent = await _templateService.RenderTemplateAsync(
"Email/MyEmailTemplate",
new MyEmailTemplateModel
{
ToFullName = "Dmitry Pavlov",
Link = "https://stackoverflow.com/users/804385/dmitry-pavlov",
SenderName = "Software in healthcare / medical device",
CustomText = "Thanks for the tip! I have got it now. Appreciate your help!"
});
This HTML
text will the output of rendered View
with the model bound to Razor
placeholders like @Model.ToFullName in this View
. I guess you will use some layout for the template view (I would recommend to embed all needed CSS
styles into it - actually you can create special _EmailTemplateLayout
file with the common HTML
markup and specify this as Layout
for all your email templates).