Handlebars-Net/Handlebars.Net

Conditional Block Helper Doesn't Work on Dynamic Object from Deserialized String

jorjen opened this issue · 4 comments

Describe the bug

I'm using the built-in #if conditional block helper. If the context data used is from an explicitly created dynamic object, it works fine. But if the dynamic object is created from a deserialized json string, it doesn't.

Expected behavior:

Should work with dynamic objects from deserialized json.

Test to reproduce

[Fact]
public void Is_Working()
{
    var handlebars = Handlebars.Create();
    var source = @"{{#if showInput}}{{input}}{{/if}}";
    var render = handlebars.Compile(source );
    var data = new { input = 42, showInput = true };
    
    var actual = render(data);
    Assert.Equal(42, actual);
}

[Fact]
public void Should_Work()
{
    var handlebars = Handlebars.Create();
    var source = @"{{#if showInput}}{{input}}{{/if}}";
    var render = handlebars.Compile(source);
    var context = @"{""input"":""42"",""showInput"":true}";
    var data = System.Text.Json.JsonSerializer.Deserialize<object>(context);
    
    var actual = render(data);
    Assert.Equal(42, actual);
}

Hello @jorjen ,
The problem is related to the fact that be default Handlebars has no idea about System.Text.Json. You need to use Handlebars.Net.Extension.Json to make it work:

[Fact]
public void Should_Work()
{
    var configuration = new HandlebarsConfiguration();
    configuration.UseJson();
    
    var handlebars = Handlebars.Create(configuration);
    var source = @"{{#if showInput}}{{input}}{{/if}}";
    var render = handlebars.Compile(source);
    var context = @"{""input"":""42"",""showInput"":true}";
    var data = System.Text.Json.JsonSerializer.Deserialize<object>(context);

    var actual = render(data);
    Assert.Equal("42", actual);
}

Hi @zjklee ,

Thank you for responding. What version are you using for Handlebars.Net?
I don't see the UseJson() method on the latest version (2.1.0) on .NET 5.0, which I'm currently using. Does this mean that the said method won't be supported in the future anymore?

https://github.com/Handlebars-Net/Handlebars.Net/blob/master/source/Handlebars/Configuration/HandlebarsConfiguration.cs

@jorjen
You need to install extension package. Follow the link in my previous comment for more details.

@zjklee
Thank you!