Git Product home page Git Product logo

razor.engine.core's Introduction

๐Ÿช’ Razor.Engine.Core

Compile and execute Razor templates outside MVC applications.

Features:

  • .NET 7.0
  • .NET 6.0
  • Windows / Linux
  • Publish as single file supported
  • Thread safe

Every single star makes maintainer happy! โญ

๐Ÿงฏ Installation

To use RazorEngineCore in a project, install the package with NuGet:

dotnet new install Razor.Engine.Core

Examples

Basic usage

RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");

string result = template.Run(new
{
    Name = "Alexander"
});

Console.WriteLine(result);

Strongly typed model

RazorEngine razorEngine = new RazorEngine();
string templateText = "Hello @Model.Name";

// yeah, heavy definition
RazorEngineCompiledTemplate<RazorEngineTemplateBase<TestModel>> template = razorEngine.Compile<RazorEngineTemplateBase<TestModel>>(templateText);

string result = template.Run(instance =>
{
    instance.Model = new TestModel()
    {
        Name = "Hello",
        Items = new[] {3, 1, 2}
    };
});

Console.WriteLine(result);

Save / Load compiled templates

Most expensive task is to compile template, you should not compile template every time you need to run it

RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");

// Save to file
template.SaveToFile("myTemplate.dll");

// Save to stream
MemoryStream memoryStream = new MemoryStream();
template.SaveToStream(memoryStream);
RazorEngineCompiledTemplate template1 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll");
RazorEngineCompiledTemplate template2 = RazorEngineCompiledTemplate.LoadFromStream(myStream);
RazorEngineCompiledTemplate<MyBase> template1 = RazorEngineCompiledTemplate<MyBase>.LoadFromFile<MyBase>("myTemplate.dll");
RazorEngineCompiledTemplate<MyBase> template2 = RazorEngineCompiledTemplate<MyBase>.LoadFromStream<MyBase>(myStream);

Caching

RazorEngineCore is not responsible for caching. Each team and project has their own caching frameworks and conventions therefore making it impossible to have builtin solution for all possible needs.

If you dont have one, use following static ConcurrentDictionary example as a simplest thread safe solution.

private static ConcurrentDictionary<int, RazorEngineCompiledTemplate> TemplateCache = new ConcurrentDictionary<int, RazorEngineCompiledTemplate>();
private string RenderTemplate(string template, object model)
{
    int hashCode = template.GetHashCode();

    RazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(hashCode, i =>
    {
        RazorEngine razorEngine = new RazorEngine();
        return razorEngine.Compile(Content);
    });

    return compiledTemplate.Run(model);
}

Template functions

ASP.NET Core way of defining template functions:

<area>
    @{ RecursionTest(3); }
</area>

@{
  void RecursionTest(int level)
  {
	if (level <= 0)
	{
		return;
	}

	<div>LEVEL: @level</div>
	@{ RecursionTest(level - 1); }
  }
}

Output:

<div>LEVEL: 3</div>
<div>LEVEL: 2</div>
<div>LEVEL: 1</div>

Helpers and custom members

string content = @"Hello @A, @B, @Decorator(123)";

RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate<CustomTemplate> template = razorEngine.Compile<CustomTemplate>(content);

string result = template.Run(instance =>
{
    instance.A = 10;
    instance.B = "Alex";
});

Console.WriteLine(result);
public class CustomTemplate : RazorEngineTemplateBase
{
    public int A { get; set; }
    public string B { get; set; }

    public string Decorator(object value)
    {
        return "-=" + value + "=-";
    }
}

Referencing assemblies

Keep your templates as simple as possible, if you need to inject "unusual" assemblies most likely you are doing it wrong. Writing @using System.IO in template will not reference System.IO assembly, use builder to manually reference it.

RazorEngine razorEngine = new RazorEngine();
RazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder =>
{
    builder.AddAssemblyReferenceByName("System.Security"); // by name
    builder.AddAssemblyReference(typeof(System.IO.File)); // by type
    builder.AddAssemblyReference(Assembly.Load("source")); // by reference
});

string result = compiledTemplate.Run(new { name = "Hello" });

Extensions

  • wdcossey/RazorEngineCore.Extensions
    • HTML values encoded by default
    • Template precompiling
    • Direct model usage without RazorEngineTemplateBase
     template.Run(object model = null)
     template.RunAsync(object model = null)
     template.Run<TModel>(TModel model = null)
     template.RunAsync<TModel>(TModel model = null)

๐Ÿ“ Contributing

If you want to contribute, great! We'd love your help!

For more in-depth information on contributing to the project and how to get started, see CONTRIBUTING.

razor.engine.core's People

Contributors

304notmodified avatar adoconnection avatar daghb avatar danielstout5 avatar krmr avatar maxnatamo avatar merlin04 avatar roja avatar spremotely avatar wdcossey avatar yazwh0 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.