• Stars
    star
    127
  • Rank 282,790 (Top 6 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 3 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library that generates HTML (e.g. for emails) from Razor Components

BlazorTemplater

A library that generates HTML (e.g. for emails) from Razor Components.

Build Nuget

Examples

The ComponentRenderer uses a fluent interface.

Let's render MyComponent.razor as a HTML string.

string html = new ComponentRenderer<MyComponent>().Render();
MyComponent.razor
<p>Hello from BlazorTemplater!</p>

Parameters

You can set parameters on a component:

var model = new Model() { Value = "Test" };
var title = "Test";
string html = new ComponentRenderer<MyComponent>()
            .Set(c => c.Model, model)
            .Set(c => c.Title, title)
            .Render();

MyComponent has a Model parameter and a Title parameter. The fluent interface uses a lambda expression to specify the property and ensures the value matches the property type.

MyComponent.razor
<h1>@Title</h1>
<p>Your model value is @Model.Value</p>
@code
{
 [Parameter] public Model Model { get; set; }
 [Parameter] public string Title { get; set; }
}

Dependency Injection

You can specify services to be provided to a component that uses @inject, e.g.:

string html = new ComponentRenderer<MyComponent>()
            .AddService<ITestService>(new TestService())
            .Render();
MyComponent.razor
@inject ITestService MyService
<p>Use service: @MyService.SomeFunction()</p>

Add Service Provider

New for version 1.5 is the ability to add your own IServiceProvider rather than adding services individually. This is useful if you need to re-use the same services repeatedly. Many thanks to @PhotoAtomic for this feature!

IServiceProvider myServiceProvider = GetServiceProvider();
string html = new ComponentRenderer<MyComponent>()
            .AddServiceProvider(myServiceProvider)
            .Render();

Layouts

If a top-level component has a @layout attribute it will be applied. Alternatively you can apply a template explicitly:

string html = new ComponentRenderer<MyComponent>()
            .UseLayout<MyLayout>()
            .Render();

You can also specify via a type:

void Example(Type layout)
{
    string html = new ComponentRenderer<MyComponent>()
            .UseLayout(layout)
            .Render();
}

See Layouts for more information

The 'kitchen sink'

You can chain them all together in any order, provided .Render() is last:

var model = new Model() { Value = "Test" };
var title = "Test";
string html = new ComponentRenderer<MyComponent>()
            .Set(c => c.Title, title)
            .AddService<ITestService>(new TestService())
            .Set(c => c.Model, model)
            .UseLayout<MyLayout>()
            .Render();
MyComponent.razor
@inject ITestService MyService
<h1>@Title</h1>
<p>Your model value is @Model.Value</p>
<p>Use service: @MyService.SomeFunction()</p>
@code
{
 [Parameter] public Model Model { get; set; }
 [Parameter] public string Title { get; set; }
}

Template Method

You can also use the older templater method (retained for compatability). See Templater

Getting Started

Add the BlazorTemplater NUGET package to your library.

Usage

See the usage guide.

Supported Project Types

BlazorTemplater can be used in

  • .NET Standard 2.0
  • .NET Standard 2.1
  • .NET Core 3.1
  • .NET 5
  • .NET 6

Libraries or applications using BlazorTemplator need to have the Razor SDK enabled to provide compilation and intellisense for .razor files. If you have an existing .NET Standard class library that does not have Razor Component support, follow this guide to upgrade the library. I did have issues retrofitting Razor support into the .NET Core 3.1 unit test app, so I moved the .razor classes into a .NET Standard library Templater.Library. This should not be an issue for a Blazor WASM or Blazor Server application using .NET Core 3.1 since they already support.

Background

Historically developers have used Razor Views (.cshtml files) to create easy-to-edit email templates with model-based data binding.

This was not a simple process as the .cshtml format wasn't always supported in non-web applications or libraries, and getting the syntax-highlighting and tooling to work with Razor Views was sometimes difficult. Two examples of this approach are RazorLight and RazorEngine.

With the introduction of Razor Component Libraries that can contain .razor files, it's now much easier to create class libraries which include Razor-based markup than using using Razor Views (.cshtml files).

Technical Differences

A .cshtml file was normally a text file or resource in a project that had to be parsed, validated, and a class generated at runtime to create code that could be used with a model to create the HTML required. The meant that RazorView-based libraries had to "compile" the template before it could be used, often at runtime.

In comparison, a Razor Component is a class created at compile time so using this is much faster and simpler! Razor Components also support binding of multiple properties (not just a single Model), so provides more flexibility in design and usage.

Supported Features

BlazorRenderer supports using:

Limitations

The following are not supported/tested:

  • JavaScript
  • EventCallbacks
  • Rerendering
  • CSS and CSS isolation

CSS and Html Emails

CSS support in HTML emails is a complicated area. Many email clients (Outlook, GMail, Hotmail etc) have differing levels of what is supported. You can't often reference an external CSS file from the email as external references are often blocked.

A good idea is to use a utility library to pre-process and inline the CSS before creating the email body. A good example of this is PreMailer.NET.

Credits and Acknowledgements

The basis of the rendering system is adapted from Steve Sanderson's BlazorUnitTestingPrototype repo which was written as very simple component test library for Blazor.

This was never developed into a functioning product or library. For unit testing Razor Components I recommend Egil Hansen's bunit.

Version History

Version Changes
v1.0.0 Inital Release (to Nuget)
v1.1.0 Breaking change: renamed BlazorTemplater class to Templater #4
v1.2.0 Added multi-targetting for .NET Std/.NET 5 to fix bug #12
v1.3.0 Added ComponentRenderer<T> for fluent interface and typed parameter setting
v1.4.0 Added support for Layouts

More Repositories

1

BlazorChatSample

A sample Blazor chat application using SignalR
C#
222
star
2

BlazorDynamicList

Demonstrates dynamic component binding for a generic list
C#
51
star
3

BlazorDynamicScriptLoad

Demonstrate dynamic loading of a JavaScript library in Blazor
HTML
17
star
4

versionReaderTask

Azure Pipelines build task to read Version tag(s) from project files
JavaScript
7
star
5

RazorTemplateClassLibrary

Demonstrates amendments to C# class library to enable IDE support for Razor templates.
C#
6
star
6

ftpclient

Implements a high-level FTP client library using the System.NET.FTPrequest library in the .NET Framework 2.0 and above
Visual Basic
6
star
7

RequireJS-Knockout-TypeScript

Sample web app using Knockout Components, with TypeScript and RequireJS
JavaScript
4
star
8

BlazorValidationLocalization

Demonstrates localisation (sic!) or localization of validation messages for Blazor forms
HTML
3
star
9

BlazorFormLayout

Helper components for rendering form content in Blazor using Bootstrap v4
HTML
3
star
10

BlazorICalendar

A Blazor ICalendar control
HTML
2
star
11

RefreshSpike

Demonstrates updating Blazor from events in an injected service, rather than polling using timers.
HTML
2
star
12

DevOpsNugetClient

Simple library for querying Nuget packages on DevOps secure feeds
C#
2
star
13

BlazorServerWithSignalR

A server-side "SignalR" example, that doesn't use SignalR!
HTML
2
star
14

NorthwindBlazor

Experiment Blazor app using Northwind as the database
C#
2
star
15

BlazorMvcExample

Experiment to see how to make MVC and Blazor co-exist
C#
1
star
16

Blazor_Angular_React

Sample app comparing Blazor, React and Angular
C#
1
star
17

BlazorServerClientIP

Demonstrates way to obtain client IP address for Blazor Server
HTML
1
star
18

TableauSample

Test project running Tableau in Blazor
HTML
1
star
19

FrankFurter

An exchange rate library using the ECB Frankfurter API
C#
1
star