I realize this is now a bit of an old question, but I came across it while investigating whether there was a "flask" way to do this, so I though I'd include how I resolved the problem.
If, like me, your javascript files include a bunch of ajax api calls and you don't want to run the risk of breaking them if you make changes, and you also don't want javascript in every template file or one massive block of inline javascript in the layout template, then this might work for you:
Create a route for the path "/js", that takes a filename as an argument, then returns a render of the filename specified.
from flask import Blueprint, abort, render_template
js = Blueprint('js', __name__, url_prefix='/js')
@js.route('/<filename>', methods=['GET'])
def file(filename):
# Prevent attempts to go outside of the js directory or return a different type of file
if "../" in filename or ".js" not in filename:
abort(404)
else:
# Go ahead and try to return the file, if it doesn't exist, return a 404
try:
return render_template("js/" + filename)
except:
abort(404)
app.register_blueprint(js.js)
Then create a folder called "js" in the templates directory of your flask project, and move all of the javascript files that require jinja to that directory.
/ {root}
|____templates
|____layout.html
|____some_other_template.html
|____js
|____myJSFile.js
Then in your templates you can use script tags that look like this:
<script src="{{ url_for('js.file', filename='myJSFile.js') }}" referrerpolicy="origin"></script>
At this point, while they appear in the html output to be being loaded like normal script links, they are actually being loaded as jinja templates, and you can use any jinja you like inside them.