I've tried plotting graphs in my Flask web app using Plotly which didn't work for some reason so I started to simplify the issue to find the error.
It seems like there is an issue with the Jinja Syntax {{ myJSONfile | safe }} in javascript.
Aslong as I pass an empty string "" to the variable the graph renders but obviously without datapoints.
(Inspect Element Console gives an Unexpected token '{' Error referring to the first opening bracket of my Jinja variable)
According to this post I should have written the the syntax inside the javascript block correctly in order to pass a JSON-File to the javascript variable and I am out of ideas right now.
I'd appreciate if somebody has further ideas and can help me out here :)
Code example:
{% extends "layout.html" %} {% block content %}
<div class=" row p-4 ">
<div class="card m-auto " style="width: 90%; " data-aos="fade-left ">
<div class="card-body ">
<div id="chart1 "></div>
</div>
</div>
</div>
<script src="https://cdn.plot.ly/plotly-latest.min.js "></script>
<script>
var graphs1 = {
{
graph1JSON | safe
}
};
Plotly.plot("chart1 ", graphs1, {});
</script>
I've since tested out another test code from a tutorial github repository to eliminate the possibility that it may have been some typing errors in my code I wasn't able to identify. But those copy paste examples gave me the same issue.
I've tried different things suggested in some posts I've found here on Stackoverflow
During debug I clearly see that the JSON file is created successfully and holds the desired data, Flask/Jinja just doesnt want to communicate with Javascript
Here's an additional Screenshot of how the syntax highlighting looks in my VS Code. (Other than in this particular case my Flask app is running fine, being able to render pages dynamically etc.)
(Syntax not recognized in the javascript part)
Please do not pull apart the jinja instruction. Jinja looks for double curly brackets in the template, which follow one another directly with no whitespace in between.
var graphs1 = {{ graph1JSON | safe }};
Plotly.plot('chart1', graphs1, {});
The problem here lies with VSCode, especially with Syntax Highlighting and Formatting Extensions. There is some conflict between some of your enabled extensions which - on save - format the javascript code in above way.
This way on save the syntax doesn't get shredded anymore making the JavaScript recognize your JSON-File correctly.