Compiling json object from string via newtonsoft causes if helper to fail
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
Handlebars.Net does not natively understand JObjects. There are two approaches to solving this:
- You can use
{{Group.basic_bool.Value}}- aJObjectproperty returns aJTokenwhich has a.Valueproperty which returns the actual underlying value. - You can use
JsonConvert.DeserializeObject<dynamic>("json")instead ofJObject. 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.
That's perfect. I've been able to prove that out in the unit tests. Thanks!