Code Monkey home page Code Monkey logo

minirazor's Introduction

MiniRazor

Build Coverage Version Downloads Donate

Project status: maintenance mode (bug fixes only).

MiniRazor is a tiny abstraction over the Razor engine, designed to provide a simple interface to compile and render templates, both at build time and at run time.

Download

  • NuGet: dotnet add package MiniRazor

Features

  • Can be used to compile and render templates at run time
  • Can be used to compile templates at build time and render them at runtime
  • Simple interface, designed for ease of use
  • Works with regular models, dynamic and anonymous objects
  • No dependency on Microsoft.AspNetCore.App shared framework or runtime
  • Targets .NET Standard 2.0+

Usage

Compile templates at build time

In most cases, you will want to compile templates at build time. This is suitable and highly recommended for scenarios where your templates are not expected to change.

To do that, first create a Razor template similar to this one:

@inherits MiniRazor.TemplateBase<string>
@namespace MyNamespace.Templates

<html>

<head>
    <title>Hello @Model</title>
</head>

<body>
    <p>Hello @Model</p>
</body>

</html>

Note the usage of @inherits and @namespace directives:

  • @inherits directive indicates that the base type of this template is MiniRazor.TemplateBase<TModel>, with the model of type string. If this directive is not included, the template will by default inherit from MiniRazor.TemplateBase<dynamic>, which doesn't provide intellisense support and type-safety when working with the model.
  • @namespace directive instructs the compiler to put the generated class into the MyNamespace.Templates namespace. If this directive is omitted, the default namespace of MiniRazor.GeneratedTemplates is used instead.

In order to make the template accessible by MiniRazor's source generator, you need to add it to the project as AdditionalFiles and mark it with the IsRazorTemplate="true" attribute:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <AdditionalFiles Include="Templates/TemplateFoo.cshtml" IsRazorTemplate="true" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="MiniRazor" Version="xxx" />
  </ItemGroup>

</Project>

Once that's done, you can run dotnet build to build the project and trigger the source generator. Given that the template's file name is TemplateFoo.cshtml, you should be able to access the generated class via MyNamespace.Templates.TemplateFoo and render it by calling the static RenderAsync(...) method:

// Reference the namespace where the template is located
using MyNamespace.Templates;

// Render the template to string, with @Model set to "world"
var output = await TemplateFoo.RenderAsync("world");

// Or, alternatively, render it to the specified TextWriter
await TemplateFoo.RenderAsync(Console.Out, "world");

Note that the type of the model parameter in RenderAsync(...) is inferred from the @inherits directive in the template. Here, since the template is derived from MiniRazor.TemplateBase<string>, the method expects a parameter of type string.

Compile templates at run time

If the previous approach doesn't fit your usage scenario, you can also compile templates at runtime. To do that, simply call Razor.Compile(...) with the template's source code:

// Compile the template into an in-memory assembly
var template = Razor.Compile("<p>Hello, @Model.Subject!</p>");

// Render the template to string
var output = await template.RenderAsync(new MyModel { Subject = "World" });
// <p>Hello, World!</p>

Calling Razor.Compile(...) compiles the supplied Razor code directly into IL loaded in-memory. The returned object can then be used to render output.

Note that, by default, MiniRazor uses the default assembly load context, which means that, once compiled, the templates will stay in memory forever. To avoid that, you can pass a custom instance of AssemblyLoadContext instead:

// Create an isolated assembly load context
var alc = new AssemblyLoadContext("MyALC", true);

// Compile the template
var template = Razor.Compile("<p>Hello, @Model.Subject!</p>", alc);

// Unload the ALC once it's no longer needed
alc.Unload();

HTML encoding

Output rendered with Razor templates is HTML-encoded by default. If you want to print raw HTML content, for example if it's sourced from somewhere else, you can use the Raw() method:

@{
    string GetHtml() => "<p>Hello world!</p>";
}

@GetHtml() // &lt;p&gt;Hello world!&lt;/p&gt; 
@Raw(GetHtml()) // <p>Hello world!</p>

minirazor's People

Contributors

tyrrrz avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.