How can I pass Python list to Javascript in HTML level

I'm trying to pass Python list to use it as Javascript array in HTML file, but when I check the passed Python list in Javascript level, the console log says it's string.

I'm trying to do that in Django environment.


def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['names'] = list(
        Store.objects.values_list('businessName', flat=True))

    return context


<span data-names="{{ names }}">...</span>

The console says it's string type. Did I miss any middle step there?

console.log result

['Michael Kors', 'Luca + Grae', 'Rebecca Minkoff', 'Aritzia', 'Nest Boutique', 'Ruby Claire Boutique', 'Bella Ella Boutique', 'Called to Surf', 'Adidas', 'Lime Lush', 'Farfetch', 'AGACI', 'The Mint Julep Boutique', 'Free People', 'Current Boutique', 'Hazel and Olive', 'DownEast Basics', 'Roolee', 'J.Crew']

2 answers

  • answered 2018-11-07 23:26 pmkro

    According to the MDN Docs all data-* attributes are saved as strings. To get a proper JSON type object you will need to use JSON.parse

    <span data-names="{{ names }}">...</span>
        const data = JSON.parse($('span').attr('data-names'));

    According to this question you can pass JSON from django (version >= 1.7) like

    from django.http import JsonResponse
    return JsonResponse({'foo':'bar'})

  • answered 2018-11-08 00:18 Ykh

        var names = {{ names|safe }}

    safe tag is one option.