Home > Blockchain >  Print Django model data as JavaScript Array
Print Django model data as JavaScript Array

Time:05-24

I have printed a for loop as below in my HTML Template:

                <td> 
                {% for athlete in booking.athlete.all %}
                {{athletes.id}}
                {% endfor %}
                </td>

The Output in HTML is as below.

<td> 
                
                1
                
                2
                
                3
                
                </td>

Is it possible to get the output to appear as [ "1", "2", "3" ], so we can then use this as a JS array or object?

I have tried a few things from the Django Template but it does not remove the additional white space.

CodePudding user response:

The easiest way is probably to use a custom template tag to get the list of athlete.ids, and then the built-in json_script filter to render those ids as json.

Let's assume your app name is myapp. If you don't have any custom filters yet, create the directory myapp/templatetags/, and add an empty __init__.py file. Then in the file myapp/templatetags/myapp_filters.py add:

from django import template

register = template.Library()

@register.filter
def qs_to_id_list(qs):
    return list(qs.values_list('id', flat=True))

In your template example, you would do:

{% load myapp_filters %}
{% for booking in bookings %}
  <tr>
    <td>{{booking.id}}</td>
    <td>{{booking.program_type}}</td>
    <td>{{booking.booking_time}}</td>

    {# set a unique script id for easier access in javascript #} 
    {% with script_id='athletes-data-'|add:booking.id %}
        {{booking.athlete.all|qs_to_id_list|json_script:script_id}}
    {% endwith %}
  </tr>
{% endfor %}

The json_script filter will render a block like this (in each table row):

<script id="athletes-data-5" type="application/json">[1, 2, 3]</script>

which can be accessed in your client-side javascript.

  • Related