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 !
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.