簡體   English   中英

將用戶定義的 html 模板與用戶定義的 json 數據合並

[英]Merge user defined html template with user defined json data

我正在嘗試創建通用實用程序類來構建電子郵件模板正文,其中包含兩個輸入

  1. 帶有占位符的 html 模板(它可以有重復的記錄)
  2. json數據

預期輸出是結合 html 模板和 jsondata 生成 html 文件。 由於我事先不知道所有模板或 json 數據模式,因此我可能必須使用 Dynamic/Expando 對象或與 Json 解析相關的類

這是示例示例 html

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

樣本數據

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

我曾嘗試使用https://github.com/lunet-io/scribanhttps://www.nuget.org/packages/Newtonsoft.Json/但無法解決這些問題。 我願意接受其他建議

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

            JObject jsonObject = JObject.Parse(jsonData);

            return template.Render(jsonObject);
 }

您可以反序列化該對象,並且(如果它很簡單)將其映射到 Scriban 的腳本對象。

像這樣:

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

希望能幫助到你,

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM