Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

url_for is not defined in Flask

Tags:

python

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

like image 486
High schooler Avatar asked Dec 20 '22 20:12

High schooler


2 Answers

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>

like image 122
rdodev Avatar answered Jan 02 '23 15:01

rdodev


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)
like image 31
plaes Avatar answered Jan 02 '23 15:01

plaes