车把 - 内联解码上下文并填充模板



我有一个包含JSON但已编码的json。容器 2 中的数据字段是一个字符串。我想在 JSON 中使用此数据和其他字段来填充模板。

var data = {
      "containers": [
        {
          "containerId": 1,
          "containerLabel": "1",
          "dataType": "URL",
          "data": "http://www.google1.com",
          "dataEncoding": null,
          "startDTS": "2019-04-03T10:41:04.570Z",
          "endDTS": "2025-01-01T18:29:59.999Z",
          "containerAnalyticsData": {
            "variationId": "563601179",
            "actionBlockId": "29408_563601179ActionBlock_0",
            "campaignId": 29408,
            "containerId": "1",
            "controlGroupId": "23517",
            "treatmentId": "8f3b53a9-1a7e-4fbe-b28f-450fa88ab474"
          }
        },
        {
          "containerId": 2,
          "containerLabel": "2",
          "dataType": "application/json",
                  "data": "{"cardType":"123Stock","cardTypeID":5,"cardID":"/content/help/en/ccx/v1/stock/width/2/stock-search","cardName":"123 Stock","displayTemplate":"123Stock","width":2,"backgroundImage":"https://helpx.123.com/content/dam/help/en/ccx/stock/stock-june2017-2w-730x280.jpg","backgroundFillColor":"","invertPresentation":false,"overlayTintColor":"","overlayTintPercentage":0.0,"priority":1,"cardLabel":"GET TEN FREE IMAGES FROM 123 STOCK","displayText":"Get 10 free 123 Stock images.","displayTextAlignment":"center","bodyCopy":"","bodyCopyAlignment":"left","ctaLabel":"Go","ctaAlignment":"right","secondaryCTALabel":"","secondaryCTAAlignment":"right","actionURL":"https://stock.123.com/search?k=","urlLinkType":"external","defaultURL":"https://stock.123.com","urlAppendAnalyticsParams":true,"urlApply123Authentication":true,"footnote":"","searchLabel":""}",
          "dataEncoding": null,
          "startDTS": "2019-04-03T10:41:04.493Z",
          "endDTS": "2025-01-02T07:59:59.999Z",
          "containerAnalyticsData": {
            "variationId": "563597567",
            "actionBlockId": "28018_563597567ActionBlock_0",
            "campaignId": 28018,
            "containerId": "2",
            "controlGroupId": "",
            "treatmentId": "PR-91a1350b-1f86-46f4-8193-0e06fbc9412d"
          }
        }]
    };

有没有办法内联解码这些数据并填充模板?

这是小提琴链接,它具有填充模板的逻辑:http://jsfiddle.net/agoyal/38goqau5/6/

编辑:
生成的对象应具有 JSON 中的内部数据元素,而不是字符串。

我快到了。我想构建自己的对象,但有一个小问题,我现在必须使用 data.data 而不仅仅是数据。如何通过修改当前上下文来返回整个对象?
看到这个小提琴:jsfiddle.net/agoyal/0fwm768n/29

你可以做的是创建一个将字符串解析为 JSON 的帮助程序。

看看这个小提琴

<div>
   {{data.cardID}}
</div>

Handlebars.registerHelper('eachJson', function(context, options) {
    let returnValue = ""
  $.each(context, function() {
    if (this.dataType === "application/json") {
      const json = JSON.parse(this.data)
      returnValue += options.fn({
        //Return the whole JSON
        data: json
      });      
    } else {
        returnValue += options.fn({
                data: this.data
      })
    }
  })
    return returnValue;
})

编辑:

最新更新