Provide Custom Value Binder in Handlebars.NET

496 Views Asked by At

I'm trying to build a code generation framework using .net core and handlebars and I would need to customize how expressions are mapped to values in handlebars.net. Is it something that is possible? The closest I've been to is to transform my input object to a dictionary, but it does not give me the flexibility I need, is there any interfaces I can implement to achieve that?

2

There are 2 best solutions below

0
On

I ended up creating a custom interface that transform any object to dictionary. Here's is the current implementations, if anyone ever need this eventually.

public interface IHandlebarsContextConverter
{
    IDictionary<string, object> Convert(object @object);
}

public class HandlebarsContextConverterFields : IHandlebarsContextConverter
{
    public IDictionary<string, object> Convert(object @object)
    {
        return @object.GetType()
            .GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .ToDictionary(x => x.Name, x => x.GetValue(@object));
    }
}

public class HandlebarsContextConverterProperties : IHandlebarsContextConverter
{
    public IDictionary<string, object> Convert(object @object)
    {
        return @object.GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .ToDictionary(x => x.Name, x => x.GetValue(@object, null));
    }
}

var converter = new HandlebarsContextConverterMerge(
        new HandlebarsContextConverterFields(),
        new HandlebarsContextConverterProperties());
0
On

If I get your intent right you can have a look at Handlebars.CSharp > IObjectDescriptorProvider (usage example).

P.S. Handlebars.CSharp is a fork of Handlebars.Net maintained by me.

Update:

Mentioned functionality is already merged to Handlebars.Net