1

I am facing some problems trying to access a context variable in my django views in my html javascript. I would like to access 'unclean' context which is a list and USE IT AS A LIST in my html script tag. Any help is appreciated. Thank you. Below are some of my code:

views.py

context = { 
  'unclean' : unclean
       }
  • Have you tried to use **`{{ unclean }}`**? – JPG Dec 30 '19 at 03:24
  • Yes. However, accessing the variable like this in javascript makes it a 'string' type. I need to use it as an 'array' type in javascript for manipulation. Thanks for the help. – Ang Yang Cheng Dec 30 '19 at 03:27

2 Answers2

0

Here is a demo of latest version, which is similar to your case.

python code

from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

HTML code:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
yansainity
  • 156
  • 6
  • I did not downvote, I was just going through the [review queues](https://meta.stackexchange.com/questions/161390/what-are-the-review-queues-and-how-do-they-work) as someone else has flagged your post as low quality (link only). To prevent this from happening again, I recommend reading the [How do I write a good answer](https://stackoverflow.com/help/how-to-answer?) help page. – Gino Mempin Dec 30 '19 at 04:04
  • Thank you! Still I cannot agree that someone else did that, he could write his answer or just remind me. It's a quite simple question. – yansainity Dec 30 '19 at 04:15
0

You can use the json_script tag to include a python object as a JS variable in your template

{{ unclean|json_script:"unclean-data" }}

<script>
    var unclean = JSON.parse(document.getElementById('unclean-data').textContent);
</script>
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50