Opened 3 years ago

Closed 3 years ago

#33469 closed New feature (duplicate)

Make ID argument of json_script filter optional

Reported by: Adam Johnson Owned by: nobody
Component: Template system Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Currently the json_script filter requires an ID. This is burdensome in loops, as one then has to unique ID's, perhaps in the view.

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 %}

Change History (1)

comment:1 by Adam Johnson, 3 years ago

Resolution: duplicate
Status: newclosed

What the heck, when I look on the main branch I discover this has already been done in #33302. Great minds...

Note: See TracTickets for help on using tickets.
Back to Top