简体   繁体   中英

Merge user defined html template with user defined json data

I am trying to create generic utility class that builds email template body taking in two inputs

  1. html template with placeholders (it can have repeating records)
  2. json data

Expected output is to generate html file combining html template and jsondata. As I do not know all the templates or json data schema in advance, I may have to use Dynamic/Expando object or classes related to Json parsing

Here's the example Sample html

<ul id='products'>
  {{ for product in products }}
    <li>
      <h2>{{ product.name }}</h2>
           Price: {{ product.price }}
           {{ product.description }}
    </li>
  {{ end }}
</ul>

Sample Data

{
  "products": [
    {
      "name": "Ball",
      "price": 788.0,
      "description": "Matches Ball"      
    },
    {
      "name": "Bat",
      "price": 2000.0,
      "description": "Wooden Bat"     
    }
  ]
}

I have tried using https://github.com/lunet-io/scriban and https://www.nuget.org/packages/Newtonsoft.Json/ but could not get around the issues. I am open to other suggestions

 public string RenderHtml(string templateHTML, string jsonData)
 {
            Scriban.Template template = Scriban.Template.Parse(templateHTML);

            JObject jsonObject = JObject.Parse(jsonData);

            return template.Render(jsonObject);
 }

You can deserialize the object and -if its simple- map it to a Scriban' script object.

Like this:

private static string GenerateTemplate()
{
  ExpandoObject reportData = JsonConvert.DeserializeObject<ExpandoObject>("{\"name\": \"Alejandro\"}");

  var scriptObject = new Scriban.Runtime.ScriptObject();
  foreach (var prop in obj)
  {
    scriptObject.Add(prop.Key, prop.Value);
  }
  var template = Template.Parse("<h1>{{name}}</h1>");
  return template.Render(scriptObject, member => LowerFirstCharacter(member.Name));
}

private static string LowerFirstCharacter(string value)
{
    if (value.Length > 1)
        return char.ToLower(value[0]) + value.Substring(1);
    return value;
}

Hope it helps,

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM