Coder Social home page Coder Social logo

wdcossey / razorenginecore.extensions Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 5.0 6.16 MB

Extensions for RazorEngineCore (ASP.NET Core 3.1.1 Razor Template Engine)

C# 88.46% HTML 9.05% CSS 2.13% JavaScript 0.36%
razor-pages razor-template-engine razor-engine razor-engine-core asp-net-core razorengine razorengine-alternative

razorenginecore.extensions's Introduction

Logo

RazorEngineCore.Extensions

Extensions for RazorEngineCore (ASP.NET Core 3.1.1 Razor Template Engine)

Build status Nuget status

HTML (safe) encoded output by default using RazorEngineCorePageModel or RazorEngineCorePageModel<T>.

RazorEngineCore.Precompiler

Template pre-compiler for RazorEngineCore.

Compile your RazorEngineCore Templates when building your solution/project, thus compiling them during runtime.

Build status Nuget status


Precompiler usage

// Setup the template for the precompiler
[assembly: PrecompiledTemplate("sample", typeof(RazorEngineCorePageModel), "@Model.Name")]

// Using the precompiled template
var resourceTemplate = await PrecompiledTemplate.LoadAsync("sample");
await resourceTemplate.RunAsync(model: someModel);
  • The precompiler tool will run after a build.
  • Scanning the output assemblies for PrecompiledTemplateAttribute.
  • Build the templates and store them in a resource file named RazorEngineCore.templates.

Support for (some) @Html tags with custom RazorEngineCoreHtmlWriter (to reduce external dependencies)

use: @("<div>string</div>")
out: &lt;div&gt;string&lt;/div&gt;

use: @Html.Encode("<div>string</div>")
out: &amp;lt;div&amp;gt;string&amp;lt;/div&amp;gt;

use: @Html.AttributeEncode("<div>string</div>")
out: &amp;lt;div&gt;string&amp;lt;/div&gt;

use: @Html.Raw("<div>string</div>")
out: <div>string</div>

Using the default RazorEngineTemplateBase with @Html will result in an exception The name 'Html' does not exist in the current context.


Extension Methods

For RazorEngine

CompileFromFile(string fileName, ...)
CompileFromFileAsync(string fileName, ...)
CompileFromStream(StreamReader streamReader, ...)
CompileFromStreamAsync(StreamReader streamReader, ...)

For RazorEngineCompiledTemplate<>

These enable direct Model usage w/o the need for the RazorEngineTemplateBase (PageModel) instance.

Run(object model = null)
RunAsync(object model = null)
Run<TModel>(TModel model = null)
RunAsync<TModel>(TModel model = null)

Coming Soon

  • Aditional @Html tags.
  • Unit Tests.
  • And more...

Razor image by Freepik

razorenginecore.extensions's People

Contributors

304notmodified avatar dependabot[bot] avatar wdcossey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

razorenginecore.extensions's Issues

Trailing delimiter is discarded

On html rendering, it discards trailing delimiter ( " or ' )

Code to reproduce:

using System;
using System.Threading.Tasks;
using RazorEngineCore;

namespace SampleApp
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            RazorEngine razorEngine = new RazorEngine();
            var template =
                await razorEngine.CompileAsync<RazorEngineCorePageModel>(
                    @"<img href='@(""test"")'>");
            var res = await template.RunAsync();
            // Observed: trailing ' is lost
            Console.WriteLine(res);
            Console.ReadKey();
        }
    }
}

Project:

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

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

  <ItemGroup>
    <PackageReference Include="RazorEngineCore" Version="2021.3.1" />
    <PackageReference Include="RazorEngineCore.Extensions" Version="0.3.0" />
  </ItemGroup>

</Project>

Patch to implement Html.PartialAsync

Using @Html.PartialAsync in template causes error.

Add partial support using code like

  protected async Task<IHtmlstring> PartialAsync<T>(string viewName, T model)
        {
            // http://stackoverflow.com/questions/483091/render-a-view-as-a-string
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return new Htmlstring  (sw.GetStringBuilder().ToString());
            }
        }

Cast error

Tried to use Html extension support in ASP .NET MVC 6 Core using

           var compiledTemplate = (IRazorEngineCompiledTemplate<RazorEngineCorePageModel<TModel>>)TemplateCache.GetOrAdd(templateHashCode, i =>
(IRazorEngineCompiledTemplate<RazorEngineCorePageModel<TModel>>)TemplateCache.GetOrAdd(templateHashCode, i =>
            {
                var razorEngine = new RazorEngine();
                var compiledTemplate = razorEngine.Compile<RazorEngineTemplateBase<TModel>>(template, builder =>
                {
                });
                return compiledTemplate;
            });

but got exception

An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'RazorEngineCore.RazorEngineCompiledTemplate1[RazorEngineCore.RazorEngineTemplateBase1[System.Object]]' to type 'RazorEngineCore.IRazorEngineCompiledTemplate1[RazorEngineCore.RazorEngineCorePageModel1[System.Object]]'.

Using original tempales with

var compiledTemplate = (IRazorEngineCompiledTemplate<RazorEngineTemplateBase<TModel>>)TemplateCache.GetOrAdd(templateHashCode, i =>
works OKJ

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.