Passing JSON data to the front end using Django

后端 未结 5 2097
旧巷少年郎
旧巷少年郎 2021-01-01 02:42

Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?

For example, if I want to send an object t

5条回答
  •  抹茶落季
    2021-01-01 02:48

    As of Django 2.1 there is another way to pass JSON objects to the front-end by including them in the template and using the json_script template filter. This will create a script tag in the HTML and include the JSON within that. This is useful for including the JSON in the download of the HTML page.

    Your template would use the tag like so:

    {{ your_json_object | json_script: "element_id" }}
    

    Where your_json_object is a template variable containing an object that can be parsed into JSON.

    The HTML output would be:

     
    

    And you can access it in a later Javascript file with:

    let my_json = JSON.parse(document.getElementByID('element_id').textContent)
    

    Checkout the documentation.

提交回复
热议问题