3

有人知道如何将 Json 数据绑定到 HandleBar 吗?

这是来源:https ://github.com/rexm/Handlebars.Net

我可以检查这个例子:

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);

它工作正常,但我将数据转换为 json,而且,我需要在 html 中进行迭代。例如,这可能是 json:

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

谢谢

4

2 回答 2

0

也可以在不声明实体类的情况下使用 json 字符串作为上下文数据。我使用了来自 Newtonsoft.Json 库和Handlebars.Net的DeserializeObject方法

例子:

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);

它还支持 JSON 嵌套对象和数组

于 2021-03-09T17:16:49.090 回答
0

****编辑 09/01**** 澄清一下,您不需要使用 JSON.Net 或任何其他实用程序将以下对象转换为 JSON。Handlebars.Net 根据类属性为您做到这一点。

.

****原来的****

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;}
}

修改上面的代码:

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

    //Code to populate data goes here

    var result = template(data);

您的模板 HTML 可能如下所示:

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

有关“每个”助手的更多信息可以在这里找到:内置助手

于 2016-08-31T20:40:25.233 回答