A few weeks ago I watched an episode of the ASP.NET Community Standup that was recorded with Sebastien Ros where they covered updates around the Orchard Core CMS product. While Orchard Core appears to be coming along nicely, one of the demos in particular caught my eye, in that it has support for Liquid templates built in. Years ago, I had utilized Liquid when doing some work with Shopify and I remembered coming away fairly impressed at how easy it was to use (here’s an intro to Liquid on the Shopify blog.) The demo piqued my interest to see how Orchard Core supported Liquid, and to see how hard it might be to add similar support into something that I might build myself. Fortunately, Orchard Core is all open source, so it was easy enough to track down that it is using a package named Fluid.Core that is maintained by Sebastien Ros.

The steps getting going are pretty straight forward. (I will show a few samples below from a little proof of concept app that I built called FluidTagHelper, so check that out if you want to just browse some code instead.)

First, obviously you need to add the Fluid package. Currently, Fluid.Core is in prerelease so…

dotnet add package Fluid.Core --version 1.0.0-beta-9399

Then, before you can render a template, you need to white list the Types that will be used in the template. Think of these as similar to your View Model types. The easiest way is to register an entire class at startup (but you can also define specific members). For example, in my TagHelper demo I registered a Fruit type during Startup.

TemplateContext.GlobalMemberAccessStrategy.Register<Fruit>();

Now, in a view you can take a template string and some data, and call FluidTemplate.TryParse and then construct a TemplateContext to render the data with. In my demo app, this is split between the Index.cshtml.cs and the FluidTagHelper.cs.

string fluidTemplate = @"<ul class=""list-group"">
{% for fruit in model %}
<li class=""list-group-item"">{{fruit.Name}} - {{fruit.Weight}} lbs</li>
{% endfor %}
</ul>";

Fruit[] fluidModel = new[]
{
    new Fruit()
    {
        Name = "Banana",
        Color = "Yellow",
        Weight = 0.75m
    },
    new Fruit()
    {
        Name = "Orange",
        Color = "Orange",
        Weight = 1.0m
    }
};

if (FluidTemplate.TryParse(fluidTemplate, out var template))
{
    var templateContext = new TemplateContext();
    templateContext.SetValue("model", fluidModel);
    string renderedTemplate = template.Render(templateContext);
}

And that’s it in a nutshell! I think that Liquid templating could be useful in any scenario where you may want a (fairly technical) end user to be able to customize application views, or even for an application developer who may want to customize various displays without having to redeploy new code. Fluid.Core looks to be a nice option that is coming along in the ASP.NET Core space.

Comments


Comments are closed