4

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.