简体   繁体   中英

How do I display a global variable from one python file into another(as a Jinja Template)

I have a file called main.py wherein all my methods are saved. There is also a Global variable called 'bayy' which I want to display it in my jinja2 template(main.html)

To make things clear: main.py

global bayy

main.html

<div>{{ bayy }}</div>

However this gives an error

jinja2.exceptions.UndefinedError: 'bayy' is undefined

How do I go about solving this error?

EDIT : I am rendering the main.html in my main.py as

def stats()
    global bayy
    #rest of code
    return render_template('main.html')

use the global g to make bayy variable available globally in your templates.

refer to https://flask.palletsprojects.com/en/1.1.x/api/#application-globals

in main.py

from flask import g, ..

def stats()
    # global bayy  # You don't need this
    # rest of code

    g.bayy = 'bayy'

    return render_template('main.html')

in main.html

<div>{{ g.bayy }}</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM