Handlebars.Net icon indicating copy to clipboard operation
Handlebars.Net copied to clipboard

Compiling json object from string via newtonsoft causes if helper to fail

Open czuroski opened this issue 10 years ago • 2 comments

I am attempting to inflate a newtonsoft JObject from a json string and then use an if helper in my template to render certain pieces of code. However, the condition for the if helper is never evaluated properly. It seems that as I step through the hb code, the value of the helper arg is always undefined. See the following unit tests to see the issue -

[Test]
public void BasicIf_WithParsedJsonObject_TrueNonLiteral()
{
    var jsonTrue = @"{ ""Group"" : { ""basic_bool"" : true } }";

    var source = "{{Group.basic_bool}} Hello, {{#if Group.basic_bool}}Bob{{else}}Sam{{/if}}!";
    var template = Handlebars.Compile(source);
    var trueData = JObject.Parse(jsonTrue);

    Console.WriteLine(trueData);
    var resultTrue = template(trueData);
    Assert.AreEqual("true Hello, Bob!", resultTrue);
}

[Test]
public void BasicIf_WithParsedJsonObject_TrueLiteral()
{
    var jsonTrue = @"{ ""Group"" : { ""basic_bool"" : 'true' } }";
    var source = "{{Group.basic_bool}} Hello, {{#if Group.basic_bool}}Bob{{else}}Sam{{/if}}!";
    var template = Handlebars.Compile(source);
    var trueData = JObject.Parse(jsonTrue);

    Console.WriteLine(trueData);
    var resultTrue = template(trueData);
    Assert.AreEqual("true Hello, Bob!", resultTrue);
}

Note that in the unit test template, I am rendering the value contained within the basic_bool field correctly, it just doesn't seem to evaluate correctly in the helper.

Thanks

czuroski avatar Apr 27 '16 20:04 czuroski

Handlebars.Net does not natively understand JObjects. There are two approaches to solving this:

  1. You can use {{Group.basic_bool.Value}} - a JObject property returns a JToken which has a .Value property which returns the actual underlying value.
  2. You can use JsonConvert.DeserializeObject<dynamic>("json") instead of JObject. That produces an ExpandoObject which behaves more like you are probably expecting. There are examples of that in the DynamicTests class in the unit test project.

rexm avatar Apr 28 '16 00:04 rexm

That's perfect. I've been able to prove that out in the unit tests. Thanks!

czuroski avatar Apr 28 '16 01:04 czuroski