0

I have the following:

views.py:

   return render_template('test.html',
                           title='Home',
                           labels = output_labels)

test.html:

<script src="{{ url_for('static', filename='js/demo.js') }}"></script>
<script type="text/javascript">
        var labelsx = {{ labels|tojson }};
 </script>

demo.js:

Chartist.Pie('#chartPreferences', {
  labels: ['{{labelsx}}'],
  series: [62, 32, 6]
});

It looks like that demo.js is not recognizing the labelsx variable at all (tried without brackets as well). The labelsx variable before "tojson" is a list:

print type(output_labels)
print output_labels

<type 'list'>
[u'string1', u'string2', u'string3']

What am I doing wrong ?

EDIT: In my opinion it is different to Passing variables from flask to javascript since I had suggested code already in place and as per accecpted answer here, the problem was in the order of defining the variable used by .js later on - which is not mentioned in that older question. Thanks !

Pitr
  • 51
  • 1
  • 11
  • Possible duplicate of [Passing variables from flask to javascript](https://stackoverflow.com/questions/37259740/passing-variables-from-flask-to-javascript) – Wombatz Jun 16 '17 at 19:59

1 Answers1

0

I think you need to move your definition of labelsx to before you load the JavaScript that uses it.

<script type="text/javascript">
  var labelsx = {{ labels|tojson }};
</script>
<script src="{{ url_for('static', filename='js/demo.js') }}"></script>

And then in demo.js, you just need to use the variable directly. It seems like you're treating it like a server-side variable in a template, but your JavaScript is being processed as a template at all:

Chartist.Pie('#chartPreferences', {
  labels: labelsx,
  series: [62, 32, 6]
});

UPDATE

I would personally prefer to expose a function from demo.js and then call it from your HTML. This avoids creating the global variable labelsx. So, demo.js:

function drawChart(labels) {
  Chartist.Pie('#chartsPreferences', {
    labels: labels,
    series: [62, 32, 6],
  });
}

And test.html:

<script src="{{ url_for('static', filename=js/demo.js') }}"></script>
<script>
  drawChart({{ labels|tojson }});
</script>
user94559
  • 59,196
  • 6
  • 103
  • 103
  • Great, it turned out that I just had to define `labelsx` before calling `demo.js`. Suggestion regarding global variable is appreciated as well! Thanks. – Pitr Jun 16 '17 at 20:06