Home > Uncategorized > Server side templating in .NET Core with #Razor

Server side templating in .NET Core with #Razor

Templating is extremely common, and is used to separate the data (often in JSON) from the presentation layer, which can either be on the client side (Mustache, Angular, Vue, React) , or on the server side (ASP.NET, Razor, etc.)

The template is typically hard-coded so that the data changes, but the template used to render that data in a presentable way is fixed. However, in certain circumstances, you may want to offer the ability to the user to change the template.

This could be in a situation where you want to offer full flexibility in presentation to the end-customer. Perhaps you want them to be able to style their own webpage, user portal, or report, or pdf. In this case, allowing both a dynamic template applied to dynamic data can offer much more flexibility.

This approach demonstrates the use of Razor, which is used commonly in modern .NET web apps, although it requires a very technical user, and could potentially cause some security issues, if the end user were to inject malicious code into the template.

So, without further Ado, let’s take a look at this project.

First, I’ll define some data as follows;

{
  "Company": "Microsoft",
  "Directors": [
    "Bill Gates",
    "Steve Ballmer"
  ]
}

Which I save as data.json, and set the property to “Copy always” in Visual Studio.

Then I define a template like so;

@Model.Company, has @Model.Directors.Count directors which are: @foreach (var Director in Model.Directors) { @String.Concat(Director," ") }

Which is designed to read “Microsoft has 2 directors which are Bill Gates Steve Ballmer”, this would be saved as “template.html” in the project.

Now, I Install the relevant NuGet packages, and usings;

using Newtonsoft.Json.Linq;  // Install-Package Newtonsoft.JSON
using RazorEngine; // Install-Package RazorEngine.NetCore
using RazorEngine.Templating;

And finally, put it all together as follows;

var data = File.ReadAllText("data.json");
var template = File.ReadAllText("template.html");
dynamic model = JObject.Parse(data);
var result =
Engine.Razor.RunCompile(
    template,
    "template",
    null,
    (object)model);
Console.WriteLine(result);

Viola!

The github repo for this project is available here: https://github.com/infiniteloopltd/RazorTemplating

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: