Skip to main content

RazorBlade by Lucas Trzesniewski

Nuget / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: RazorBlade

Compile Razor templates at build-time without a dependency on ASP.NET.

Author: Lucas Trzesniewski

NuGet: https://www.nuget.org/packages/RazorBlade/

You can find more details at https://github.com/ltrzesniewski/RazorBlade

Source : https://github.com/ltrzesniewski/RazorBlade

Original Readme

note

RazorBlade

Build NuGet package GitHub release License

The sharpest part of the razor.

Compile Razor templates at build-time without a dependency on ASP.NET.

Usage

This package will generate a template class for every .cshtml file in your project.

The generated classes will inherit from RazorBlade.HtmlTemplate by default, though it is advised to specify the base class explicitly to get the best IDE experience:

@inherits RazorBlade.HtmlTemplate

A version with a model is also available for convenience. The following will add a Model property and a constructor with a TModel parameter:

@inherits RazorBlade.HtmlTemplate<TModel>

Further documentation is provided below.

Example

The following template, in the TestTemplate.cshtml file:

@inherits RazorBlade.HtmlTemplate

Hello, <i>@Name</i>!

@functions
{
public string? Name { get; set; }
}

Will generate the following class in your project:

internal partial class TestTemplate : RazorBlade.HtmlTemplate
{
// ...
public string? Name { get; set; }
// ...
}

That you can use like the following:

var template = new TestTemplate
{
Name = "World"
};

var result = template.Render();

With a model

A similar template with a model would be:

@using MyApplication.Models
@inherits RazorBlade.HtmlTemplate<GreetingModel>

Hello, <i>@Model.Name</i>!

Instantiating the generated class requires a model argument:

var model = new GreetingModel { Name = "World" };
var template = new TestTemplate(model);
var result = template.Render();

Documentation

Base template classes

For HTML templates, specify one of the following base classes with an @inherits directive:

  • RazorBlade.HtmlTemplate
  • RazorBlade.HtmlTemplate<TModel>

If you'd like to write a plain text template (which never escapes HTML), the following classes are available:

  • RazorBlade.PlainTextTemplate
  • RazorBlade.PlainTextTemplate<TModel>

They all derive from RazorBlade.RazorTemplate, which provides the base functionality.

You can also write your own base classes. Marking a constructor with [TemplateConstructor] will forward it to the generated template class.

Writing templates

HTML escaping can be avoided by using the @Html.Raw(value) method, just like in ASP.NET. The IEncodedContent interface represents content which does not need to be escaped. The HtmlString class is a simple implementation of this interface.

Templates can be included in other templates by evaluating them, since they implement IEncodedContent. For instance, a Footer template can be included by writing @(new Footer()). Remember to always create a new instance of the template to include, even if it doesn't contain custom code, as templates are stateful and not thread-safe.

The namespace of the generated class can be customized with the @namespace directive. The default value is deduced from the file location.

Executing templates

The RazorTemplate base class provides Render and RenderAsync methods to execute the template.

Templates are stateful and not thread-safe, so it is advised to always create new instances of the templates to render.

MSBuild

The source generator will process RazorBlade MSBuild items which have the .cshtml file extension.

By default, all .cshtml files are included, unless one of the EnableDefaultRazorBladeItems or EnableDefaultItems properties are set to false. You can also manually customize this set.

Removing the dependency on RazorBlade

RazorBlade makes it possible to remove the dependency on its runtime assembly. This could be useful for library projects which should be self-contained, with no dependencies on external packages.

This mode is enabled by default when the PackageReference of RazorBlade has the PrivateAssets="all" attribute. In order to avoid compilation warnings, the assembly reference also needs to be explicitly excluded with ExcludeAssets="compile;runtime".

<PackageReference Include="RazorBlade" Version="..." ExcludeAssets="compile;runtime" PrivateAssets="all" />

A source generator will then embed an internal version of the RazorBlade library in the target project. This behavior can also be controlled by setting the RazorBladeEmbeddedLibrary MSBuild property to true or false.

About

note

Fast templating with Razor syntax

Do not forget to put into AdditionalFiles section of csproj file

How to use

Example ( source csproj, source files )

This is the CSharp Project that references RazorBlade

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RazorBlade" Version="0.4.3" PrivateAssets="all" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="PersonDisplay.cshtml" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX

// This file is part of the RazorBlade library.

#nullable enable

using System;

namespace RazorBlade.Support;

/// <summary>
/// Specifies that this constructor needs to be provided by the generated template class.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor)]
internal sealed class TemplateConstructorAttribute : Attribute
{
}

/// <summary>
/// Specifies if a method should be used depending on the template being sync or async.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
internal sealed class ConditionalOnAsyncAttribute : Attribute
{
/// <summary>
/// The message to display.
/// </summary>
public string? Message { get; set; }

/// <summary>
/// Marks a method as meant to be used in a sync or async template.
/// </summary>
/// <param name="async">True for methods meant to be used in async templates, and false for methods meant to be used for sync templates.</param>
public ConditionalOnAsyncAttribute(bool async)
{
}
}

Usefull

Download Example (.NET C# )

Share RazorBlade

https://ignatandrei.github.io/RSCG_Examples/v2/docs/RazorBlade

In the same category (Templating) - 6 other generators

Gobie

InterceptorTemplate

Microsoft.NET.Sdk.Razor.SourceGenerators

MorrisMoxy

RSCG_Templating

spreadcheetah