{{{
def charts(request):
data_sets = ...
charts = [
{"id": f"chart-data-{i}", "data": data}
for i, data in enumerate(data_sets)
]
return render(request, "charts.html", {"charts": charts})
}}}
…and use them in the template:
{{{
{% for chart in charts %}
<my-chart data-id="{{ chart.id }}">
{{ chart.data|json_script:chart.id }}
</my-chart>
{% endfor %}
}}}
If `json_script` did not need an ID, this work could be saved. The
`<script>` tag could avoid having an `id` attribute, and JavaScript could
still look up the `<script>` tag based on its position in the DOM, with
e.g. `this.element.querySelect("script[type='application/json']")`.
The template could then be simpler, and no view logic would be required:
{{{
{% for chart in charts %}
<my-chart>
{{ chart.data|json_script }}
</my-chart>
{% endfor %}
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33469>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* status: new => closed
* resolution: => duplicate
Comment:
What the heck, when I look on the main branch I discover this has already
been done in #33302. Great minds...
--
Ticket URL: <https://code.djangoproject.com/ticket/33469#comment:1>