import os
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
from flask import Flask,url_for
app = Flask(__name__)
@app.route('/')
def hello_world():
tmpl = env.get_template('index.html')
sidebar = env.get_template('sidebar.html')
return tmpl.render(root_url="",sidebar=sidebar.render())
if __name__ == '__main__':
app.run(debug=True)
and in tempaltes/index.html
{{ url_for('static', filename='js/main.js') }}
Though, I get url_for is not defined? I am trying to follow the examples online but I don't know why I get this
I think the issue is that you are trying to have code logic in the jinja html template. Jinja prohibits that, by design, so that code/presentation aren't mixed.
So, I would suggest generating the url in the code, stashing it somewhere in the object you send jinja and then using that variable in the template. Something along the lines of:
def hello_world():
tmpl = env.get_template('index.html')
sidebar = env.get_template('sidebar.html')
js_url = url_for('static', filename='js/main.js')
return tmpl.render(root_url="",sidebar=sidebar.render(), jsurl=js_url)
Then on the template side:
<script type="text/javascript" src="{{jsurl}}"></script>
It seems that you are using Flask and Jinja in a bit non-recommended way. I suggest that you use render_template
which also adds access to Flask-specific functions like url_for
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With