简体   繁体   English

将用户定义的 html 模板与用户定义的 json 数据合并

[英]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)带有占位符的 html 模板(它可以有重复的记录)
  2. json data json数据

Expected output is to generate html file combining html template and jsondata.预期输出是结合 html 模板和 jsondata 生成 html 文件。 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由于我事先不知道所有模板或 json 数据模式,因此我可能必须使用 Dynamic/Expando 对象或与 Json 解析相关的类

Here's the example Sample html这是示例示例 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.我曾尝试使用https://github.com/lunet-io/scribanhttps://www.nuget.org/packages/Newtonsoft.Json/但无法解决这些问题。 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.您可以反序列化该对象,并且(如果它很简单)将其映射到 Scriban 的脚本对象。

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!干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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