Search code examples
pythonflaskjinja2

How to create a global variable for render_template()?


I have a simple task: to pass the same variable for different routes in the render_template() function. This value is in the base template and I need to pass it on every render_template() function. Can I set this value as a global so that I don't have to set it in every function for different routes?

@app.route('/hello')
def hello(name=None):
    return render_template('hello.html', value=value)

@app.route('/bye')
def bye(name=None):
    return render_template('bye.html', value=value)

Solution

  • I found the correct solution to my question in the Flask documentation:

    Context Processors To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app:

    @app.context_processor
    def inject_user():
        return dict(user=g.user)
    

    The context processor above makes a variable called user available in the template with the value of g.user. This example is not very interesting because g is available in templates anyways, but it gives an idea how this works.