[Chartjs]-Labels attribute of chartsjs not taking context variable of type string

2πŸ‘

βœ…

I have had this exact problem. Javascript is treating your T1, T2, T3 etc. as variables. Use this instead:

var label_lst = [];
{% for number in labels_in_sortedList %}
{% for value in number.jsonSortedLabels %}
label_lst.push("{{ value }}");
{% endfor %}
{% endfor %}

Then, put your labels key as label_lst:

type: 'horizontalBar',
                    data: {
                        labels: label_lst;
...

0πŸ‘

it is evaluating your labels as variables, format it into a string with

{% for number in labels_in_sortedList %}
 {% for value in number.jsonSortedLabels %}
   {{ `${value}` }},
 {% endfor %}
{% endfor %}

0πŸ‘

you should add if statement to check whether it is null or not.

{% if len(numbers_in_sortedList) != 0 %}
  {% for number in numbers_in_sortedList %}
    {% if len(number.jsonM) != 0 %}
      {% for value in number.jsonM %}
        {{ value }},
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endif %}

-1πŸ‘

It looks like the values need to be quoted so as to be treated as strings. The resultant JavaScript array from:

{% for number in labels_in_sortedList %}
    {% for value in number.jsonSortedLabels %}
        {{ value }},
    {% endfor %}
{% endfor %}

possibly looks like:

[T1, T2, ...]

It should look like:

["T1", "T2", ...]

I don’t know Django, but presumably you can do this:

{{'"' + value + '"'}},

Edit:

Skimming the Django documentation suggests that "variables" (using {{ and }}) simply output values.

Perhaps using "tags" will work, as "Tags provide arbitrary logic in the rendering process" and also "a tag can output content":

{% '"' + value + '"' %},

Or maybe this would work but my naive assumption is that it will be output as a string literal:

"{{ value }}",

Leave a comment