I'm writing a Flask app using jinja2, and I'm trying to pass my Python variables both into some Javascript and HTML. I made Javascript and HTML templates, but for some reason the Javascript is getting rendered and displayed in the wrong place, and I can't figure out what the problem is.
My controller code that passes my Python data, and renders my templates is:
@info_page.route('/info.html', methods=['GET'])
def info():
''' Documentation here. '''
session = db.Session()
infoDict = {}
jsDict = {}
...
infoDict['character'] = character
infoDict['name']=name
jsDict['powertree']=powertree
js = render_template('powertree.js', **jsDict)
infoDict['js']=js
return render_template("info.html", **infoDict)
The template for info.html is:
{% extends "layout.html" %}
{% block head %}
<link rel="stylesheet" type="text/css" href=" {{url_for('static',filename='css/index.css')}}">
{% endblock head %}
{% block code %}
{{js}}
{% endblock code %}
{% block body %}
<h1>{{name}}</h1>
...
{% endblock body %}
And the template for powertree.js is:
<script type='text/javascript'>
$(document).ready(function() {
var data = {{powertree}};
console.log('hello, inside powertree');
});
</script>
The rendered Javascript code is just visibly printed at the top of my webpage. Looking at the DOM shows it's displayed inside the HTML body and not inside the HTML head, where it belongs. If I remove the {{js}} and replace it with the actual code inside powertree.js, everything renders fine, and works as expected. However I'd rather keep my Javascript in a separate file as it will get quite long. Why doesn't this work? How can I easily pass my variables into Javascript code so I can reference, in this example {{powertree}} in my js? Because it just visibly prints the Javascript at the top of my webpage, it makes me think it's a simple syntax error with a missing or something like that, but I can't find anything.
Thanks.