javascriptc#jsonmustache

How do I render an html block using mustache and single entity in json


I am trying to learn the mustache templating engine and I have a simple example I can't seem to figure out...

Given this json

{  
    "targetPatient": {  
        "address": {  
            "city": "Moore",  
            "country": null,  
            "lines": [  
                "123 Main Street"  
            ],  
            "state": "SC",  
            "zip": "29388"  
        },  
        "communicationList": null,  
        "dateOfBirth": "1970-02-01",  
        "gender": "M",  
        "personName": {  
            "firstName": "Johnny",  
            "lastName": "Smith"  
        }  
    }  
} 

I want to render this html

<!DOCTYPE html>
<html lang=""en"">
<head>
    <meta charset=""UTF-8"">
    <title>Title</title>
    
</head>
<body>
<H3>
Johnny Smith
</H3>
</body>
</html>

using this template...

<!DOCTYPE html>
<html lang=""en"">
<head>
    <meta charset=""UTF-8"">
    <title>Title</title>
    
</head>
<body>
<H3>
{{targetPatient.personName.firstName}} {{targetPatient.personName.lastName}}
</H3>
</body>
</html>

Was really hoping it would be that simple.

What is the simplest way to render this simple example.

I am trying to render using c# stubble library. Here is that code...

var template  = GetTemplate();  //get above template
var json = GetJson();           //get above json

//var stubble = new Stubble.Core.Builders.StubbleBuilder().Build();
//var output = stubble.Render(template, json);
var output = Nustache.Core.Render.StringToString(template,json);

var filePath = $@"<user>\Desktop\stubble\{Guid.NewGuid().ToString()}.html";

File.AppendAllText(filePath,output);

Here is what is rendered...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    
</head>
<body>
<H3>
 
</H3>
</body>
</html>

Here is .net fiddle...

https://dotnetfiddle.net/92BPoa

EDIT - example changed from using Stubble to Nustache since it is working with dotnetfiddle.net


Solution

  • I figured out that the libraries need to receive a json object not a string (that happens to be json) as the Data.

    var template = GetTemplate();
    var json = GetJson();
    
    //var stubble = new Stubble.Core.Builders.StubbleBuilder().Build();
    //var output = stubble.Render(template, json);
    var jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
    var output = Nustache.Core.Render.StringToString(template,jsonResult);
    
    var hbtemplate = HandlebarsDotNet.Handlebars.Compile(template);
    
    var output2 = hbtemplate(jsonResult);