Handlebars-Net / Handlebars.Net

A real .NET Handlebars engine
MIT License
1.24k stars 214 forks source link

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

Closed jorjen closed 2 years ago

jorjen commented 2 years ago

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);
}
oformaniuk commented 2 years ago

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);
}
jorjen commented 2 years ago

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

oformaniuk commented 2 years ago

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

jorjen commented 2 years ago

@zjklee Thank you!