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 !

1

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Great, it turned out that I just had to define labelsx before calling demo.js. Suggestion regarding global variable is appreciated as well! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.