Home > Mobile >  Uncaught SyntaxError: Unexpected token '&' '
Uncaught SyntaxError: Unexpected token '&' '

Time:12-07

I have a django website where i want to include a js graph that plots prices against dates. I use (Plotly) https://plotly.com/javascript/

My problem is when i pass an array of dates (formatted 'yyyy/mm/dd') from my view in views.py into my html file which includes the code for my graph the dates have '&#x27 ;' either side of each date.

views.py

context = {
    "dates":['2022/12/03', '2022/12/04', '2022/12/05'],
}

return render(request, "App/minifig_page.html", context=context)

inside html

<script>
...
var xArray = {{dates}};
...
</script>

xArray in browser view sources [&#x27 ;2022/12/03', &#x27 ;2022/12/04&#x27 ;, &#x27 ;2022/12/05&#x27 ;]

This causes the dates to be improperly formatted and therefore the graph does not display.

CodePudding user response:

This is not how you render a JSON blob. You can use the |json_script template filter [Django-doc]:

{{ dates|json_script:xArray }}
<script>
…
const value = JSON.parse(document.getElementById('xArray').textContent);
…
</script>

This will then JSON encode the data, and let it load with JSON.parse. It is also better that the "outer" data structure is a dictionary, not an array due to a subtle JSON vulnerability [haacked.com].

  • Related