-3

I am trying to use Django for loop in JavaScript but I am getting a syntax error:

<script>
        var config = {
        type: 'pie',
        data: {
            datasets: [{
                data: [1780000, 1630000],
                backgroundColor: [
                    '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3',       '#ffff26', '#4cff4c', '#ff00ff'
                ],
                label: 'Population'
            }],
            labels: [{% for label in labels %} {{ label }}, {% endfor %}]
        },
        options: {
            responsive: true
        }
        };
</script>

this part is what i a have a problem with to be exact

{% for label in labels %} {{ label }}, {% endfor %}

just typing:

{% for %} 

gives me a syntax error I looked at similar stack overflow questions and they just use the for loop normally without any problems so why am I getting a syntax error. I even tried it in an an empty Js file and still get a syntax error. Am I forgetting to import something? It works just fine in the HTML file.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Frost
  • 3
  • 3

1 Answers1

0

You can't directly use Django template tags in your JavaScript code. You can use them in your template files.

Please see this question to understand how to access them from JavaScript code.

Luke
  • 965
  • 8
  • 21
  • Thank you for kindly replying and referencing that question. I just had to put `{{ label }} ` between 2 quotations and the code works perfectly but it is not optimal especially for numbers and still has syntax errors. Looks like using JSON is the correct proper way. – Frost Jun 22 '22 at 19:59
  • Yes, if JS code is placed in a template file then it works. However, it is better to keep JS code is in its own files. Yes, using JSON might be a better idea, if you don't have to use template tags. You're welcome. – Luke Jun 22 '22 at 23:31