3

Does someone know how to bind Json data to HandleBar?

Here is the source: https://github.com/rexm/Handlebars.Net

I could check this example:

string source =
        @"<div class=""entry"">
          <h1>{{title}}</h1>
          <div class=""body"">
            {{body}}
          </div>
        </div>";
        var template = Handlebars.Compile(source);
        var data = new
        {
            title = "My new post",
            body = "This is my first post!"
        };

        var result = template(data);

And it works fine, but i have the data into a json, and also, i need to make iteration in the html. For example, this could be the json:

{"Threshold":12,"Server":[{"Name":"Machine1","CpuUsage":27,"RamUsage":62},{"Name":Machine2","CpuUsage":25,"RamUsage":57}]}

Thanks

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
Mati Silver
  • 185
  • 1
  • 13

2 Answers2

0

****Edit 09/01**** Just to clarify, you don't need to use JSON.Net or any other utility to convert the objects below to JSON. Handlebars.Net does that for you, based on the class properties.

.

****Original****

public class Server
{
    public string Name {get;set;}
    public int CpuUsage {get;set;}
    public int RamUsage {get;set;}
}

public class HandlebarsJson
{
    public int Threshold {get;set;}
    public List<Server> ListOfServers {get;set;}
}

Modifying your code above:

    var template = Handlebars.Compile(source);
    var data = new HandlebarsJson();

    //Code to populate data goes here

    var result = template(data);

Your template HTML may look something like this:

"<div class=""entry"">
     <h1>{{Threshold}}</h1>
     <div class=""body"">
     {{#each ListOfServers}}
         <p>{{Name}}</p>
         <p>{{CpuUsage}}</p>
         <p>{{RamUsage}}</p>
     {{/each}}
     </div>
 </div>"

More info about the "each" helper can be found here: Built-In Helpers

BobbyA
  • 2,090
  • 23
  • 41
0

It is also possible to use json string as context data without declaring entity classes. I used DeserializeObject method from Newtonsoft.Json library and Handlebars.Net

Example:

string source =
@"<div class=""entry"">
  <h1>{{title}}</h1>
  <div class=""body"">
    {{body}}
  </div>
</div>";

var template = Handlebars.Compile(source);
const string jsonContext = "{ \"title\": \"My new post\", \"body\": \"This is my first post!\" }";
var context = JsonConvert.DeserializeObject(jsonContext);

var result = template(context);

It also supports JSON nested objects and arrays