jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 80 forks source link

Enable dynamic json object as source #71

Closed cbean-ciee closed 7 years ago

cbean-ciee commented 7 years ago

I've found this library enormously useful and am currently using it from PowerShell to template some emails. I am able to marshal data between PowerShell and C# using json, but unfortunately the if-condition doesn't work with dynamic Newtonsoft.Json types.

I've added support for Newtonsoft.Json to the ConditionTagDefinition class using the dynamic keyword to avoid adding a dependency to the main assembly.

These changes allow the following (see JsonIfTests.cs for more possibilities):


   string json = "{'name': 'FirstName', ifTrue: 1}";
   string expected = "Hello, FirstName!!!";
   const string format = @"Hello{{#if ifTrue}}, {{name}}{{/if}}!!!";

   var compiler = new HtmlFormatCompiler();
   var generator = compiler.Compile(format);
   dynamic jsonObject = JsonConvert.DeserializeObject<dynamic>(json);
   string actual = generator.Render(jsonObject);
   Assert.AreEqual(expected, actual, "The wrong message was generated.");
jehugaleahsa commented 7 years ago

http://stackoverflow.com/questions/14886800/convert-jobject-into-dictionarystring-object-is-it-possible Performing this first is probably a better option. If M# receives a Dictionary<string, object>, it will deal work it.

cbean-ciee commented 7 years ago

Interesting. Thanks! I'll give that a try.

cbean-ciee commented 7 years ago

It worked great. Thank you for the suggestion.