Uncaught SyntaxError: Неожиданная лексема '&' '

У меня есть сайт на django, где я хочу включить js-график, который строит графики цен в зависимости от даты. Я использую (Plotly) https://plotly.com/javascript/

Моя проблема в том, что когда я передаю массив дат (с форматированием 'yyyy/mm/dd') из моего представления в views.py в мой html файл, который включает код для моего графика, даты имеют '&#x27 ;' по бокам от каждой даты.

views.py

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

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

внутри 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 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].

Вернуться на верх