How to pass an object from Scriban to JavaScript

  Kiến thức lập trình

I am working on a project that uses Scriban templates to render data. I have a complex object in Scriban that I need to pass to JavaScript as a usable object. When I try to pass the object directly, it seems to be incorrectly formatted or encoded. What is the correct way to set an object from Scriban to JavaScript?

Example of the problem:

Here is an example of my Scriban template:

{{
  data = [
    {
      "key": "hotsite",
      "value": [
        {
          "key": "banners",
          "value": [
            {
              "key": "alt_text",
              "value": "About the Store"
            },
            {
              "key": "banner_name",
              "value": "Winter-2024-vittal"
            },
            {
              "key": "banner_url",
              "value": "https://example.com/image.jpg"
            },
            {
              "key": "position",
              "value": "Center"
            },
            {
              "key": "url_on_click",
              "value": "https://example.com/click"
            },
            {
              "key": "open_new_tab",
              "value": false
            }
          ]
        }
      ]
    }
  ]
}}

<script>
window.DATA_EXAMPLE = "{{ data | json_encode }}";
</script>

Issue:

I get an error when trying to parse DATA_EXAMPLE, and it seems like the data is not correctly formatted when passed from Scriban to JavaScript. How can I correctly format the object in Scriban so it can be used directly in JavaScript?

LEAVE A COMMENT