Access variables defined in app.py inside base.html using jinja 2

  flask, html, jinja2, python

I want to define a variable page_title = 'YouThoob' in app.py in Flask and acces it in base.html using jinja-2 syntax without passing it as an argument in each render_template function.

Like in app.py I have

From flask import Flask, render_template

app = Flask(__name__)

page_title = 'YouThoob'

@app.route('/')
def index():
    return render_template("base.html") # I don't want to pass in page_title as an argument because I want to make things flexible

And in .html file, I want to access it like:

<title>{{ page_title }}</title>

If I run it, the title remains empty, because it is not defined.

(Many might suggest passing it as an argument only in base.html, but I don’t want to do that since my program may contain multiple base.html files. And if you think this answer is duplicate, then I’ve already done my homework and did not find any suitable. TIA)

Source: Python Questions

LEAVE A COMMENT